我在这里使用了手动编写:http://stevesouders.com/tests/jsorder.php,它给出了异步加载JS文件的以下方案:
var sNew = document.createElement("script");
sNew.type = "text/javascript";
sNew.async = true;
sNew.src = "http://yourdomain.com/main.js";
var s0 = document.getElementsByTagName('script')[0];
s0.parentNode.insertBefore(sNew, s0);我用它来加载额外的jQuery插件文件。
因此,页面结构变成了下面的内容:
<html><head>
//meta-tags, css-files loading...
array of JS files for async load (m)
code for async load
some links to js-files (like jquery.js)
</head><body>
//page content...
$(document).ready(function() {
all jQuery stuff
)};
</body></html>可能是结构有问题,但在Chrome15中打开页面时,我得到了像Object [object Object] has no method 'XXX'这样的错误,其中XXX是来自那些插件的函数,应该异步加载。
顺便说一下:在IE9中,这个问题似乎不会出现。
发布于 2012-01-18 18:56:49
问题是document.ready下的代码必须在脚本加载之前执行。您应该在$(.ready)文档中使用jQuery的getScript:
$.getScript('plugin-dependency.js', function(){
//Do Stuff with the loaded plugin
});这将确保您的代码仅在插件加载后运行。
More info about jQuery's getScript.
https://stackoverflow.com/questions/8908838
复制相似问题