动态脚本加载的最佳方式 [英] best way of dynamic script loading
问题描述
我需要动态地和顺序地加载一些js文件(即第二个加载完成后加载第二个脚本,第二个加载完第二个等等)。
I need to load some js files dynamically and sequentially(i.e. second script loads after load complete of first one, third after second and so on).
问题:如何检测脚本何时加载?我遇到了onload事件的问题 - 它不会在IE8中触发。在阅读了这个之后,我尝试订阅onreadystatechange并编写了非常难看的代码来加载脚本:
Question: how to detect when a script have been loaded? I have encountered problems with onload event - it not fires in IE8. After reading this, I tried to subscribe to onreadystatechange and wrote very ugly code for loading a script:
function loadScript(url, callback) {
var isLoaded = false;
var script = document.createElement('script');
script.onreadystatechange = function () {
if ((script.readyState == 'complete' || script.readyState == 'loaded') && !isLoaded) {
if (callback) callback();
}
};
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
document.head.appendChild(script);
};
如果没有这些技巧,你能建议更好的跨浏览器解决方案吗?
Can you suggest better cross browser solution without such tricks?
UPD:
感谢您的回答。如果我还需要加载jquery.js(例如,客户端有旧版本),我该怎么办?)?
UPD: Thanks for answers. What should I do if I need also to load jquery.js(for example, client have old version) :)?
推荐答案
我认为你需要的是 jQuery.getScript
函数采用URL和成功方法,您可以使用它来链接加载脚本,然后按顺序加载它们:
The function takes a URL and a success method with which you can chain loading of scripts and therefore load them sequentially:
jQuery.getScript( url, function() {
jQuery.getScript( url2, function()
{/*... all 2 scripts finished loading */}
);
});
这篇关于动态脚本加载的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!