懒惰加载Javascript,对象不是从IE8缓存创建的

时间:2010-05-24 11:17:13

标签: javascript caching internet-explorer-8

不幸的是,错误不会发生在我的应用程序之外!

方案

的index.php

<?php
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').'GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Lazy loader</title>
</head>
<body>
...
<script type="text/javascript" src="internal.js"></script>
...
</body>
</html>

internal.js

myApp = {
    timerHitIt: false,
    hitIt: function () {
        if (arguments.callee.done) { return; }
        arguments.callee.done = true;
        if (myApp.timerHitIt) { clearInterval(myApp.timerHitIt); }
        var elt = document.createElement("script");
        elt.async = true;
        elt.type = "text/javascript";
        elt.src = "external.js";
        elt.onload = elt.onreadystatechange = function () { alert(typeof(something)); };
        document.body.appendChild(elt);
    }
};
if (document.addEventListener) { document.addEventListener("DOMContentLoaded", myApp.hitIt, false); }
/*@cc_on @*/
/*@if (@_win32)
    document.write("<script id=__ie_onload defer src="+((location.protocol == "https:") ? "//:" : "javascript:void(0)")+"><\/script>");
    document.getElementById("__ie_onload").onreadystatechange = function () {
        if (this.readyState == "complete") { myApp.hitIt(); }
    };
/*@end @*/
if (/WebKit/i.test(navigator.userAgent)) {
    timerHitIt = setInterval(function () {
        if (/loaded|complete/.test(document.readyState)) { myApp.hitIt(); }
    }, 10);
}
window.onload = myApp.hitIt;

external.js

something = {};
alert(true);

有效结果

  • undefined - &gt;是的 - &gt;对象(±新请求)
  • true - &gt;对象(±cached javascript)

但有时,当击中F5时,我得到了

  • true - &gt;未定义

有没有人知道为什么警报(true)被执行但没有设置?

1 个答案:

答案 0 :(得分:0)

解决方案,甚至修复了Internet Explorer 6

window.something = {};