我使用动态脚本加载来减少初始页面加载的持续时间。为了确保脚本定义的函数和对象是可访问的,我需要确保脚本已经完全加载。可以信任script.readyState来检测动态脚本加载的结束吗?
为此我开发了my own Javascript library,因此做了很多关于这个主题的研究,研究它是如何在不同的库中完成的。 在与此相关的问题进行讨论,凯尔·辛普森的LABjs撰文,指出:
LABjs(和许多其他装载机)上设置的所有脚本元素 都“的onload”和“的onreadystatechange” ,知道这 有些浏览器会火一把,有的 将触发其他...
你可以找到这样的例子在the current version of jQuery as of this writing, v1.3.2:
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function(){
if (!done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
success();
complete();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
这是最先进的技术,但是在分析Opera 9.64中的一个奇怪行为时,我得出结论:使用这种技术,onload回调会被触发得太早。
我会在回答这个问题时发表自己的发现,并希望从社区收集更多的证据和反馈。
任何人都可以在jQuery 1.x-master分支中找到当前代码?看起来他们已经退出使用'.onreadystatechange'和'.onload'并用promises替换它们? [Clicky](https://github.com/jquery/jquery/blob/1.x-master/src/ajax.js) – Campbeln 2014-12-10 22:54:49