动态脚本加载的最佳方式

2xM*_*Max 6 javascript jquery internet-explorer

我需要动态地和顺序地加载一些js文件(即第一个加载完成后第二个脚本加载,第二个加载完毕后加载第三个脚本等等).

问题:如何检测脚本何时加载?我遇到过onload事件的问题 - 它不会在IE8中触发.阅读本文之后,我尝试订阅onreadystatechange并编写了非常难看的代码来加载脚本:

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);
    };
Run Code Online (Sandbox Code Playgroud)

你能否提出更好的跨浏览器解决方案而不用这些技巧?

UPD: 谢谢你的回答.如果我还需要加载jquery.js(例如,客户端有旧版本):)我该怎么办?

Pre*_*eli 10

我认为你需要的是jQuery.getScript

该函数采用URL和成功方法,您可以使用该方法链接加载脚本,然后按顺序加载它们:

jQuery.getScript( url, function() { 
  jQuery.getScript( url2, function() 
    {/*... all 2 scripts finished loading */}
  );
});
Run Code Online (Sandbox Code Playgroud)


Fla*_*ken 8

这是我使用jQuery.getScript()加载几个脚本的代码片段;

function getScripts(inserts, callback)
{
    var nextInsert = inserts.shift();
    if (nextInsert != undefined)
    {
        console.log("calling"+nextInsert);
    jQuery.getScript(nextInsert, function(){ getScripts(inserts, callback); })
            .fail(function(jqxhr, settings, exception){alert("including "+nextInsert+" failed:\n" +exception)});
    }
    else
    {
        if (callback != undefined) callback();
    }
};
Run Code Online (Sandbox Code Playgroud)

用法:

var includes = [
    "js/script1.js",
    "js/script2.js",
    "js/script3.js"
];

getScripts(includes, function(){ /* typically a call to your init method comes here */; });
Run Code Online (Sandbox Code Playgroud)