我们知道, 现代主流浏览器(如chrome)加载js是异步执行的,会同时加载多个js,那么当我们需要在js中动态加载其他的js时候,他们的完成顺序并不是像我们主观想象的那样,先写的先加载。例如:
function loadScript(url, fn) { var script = document.createElement("script"); script.type = "text/javascript"; script.src = url; script.onload = script.onreadystatechange = function () { if (!script.readyState || 'loaded' === script.readyState || 'complete' === script.readyState) { fn && fn(); } }; script.src = url; document.head.appendChild(script);} 这是一段动态加载js的代码,倘若写成:loadScript("http://cdn.bootcss.com/Chart.js/2.0.0-alpha3/Chart.js",function(){document.getElementById("test").innerHTML+="chart;"}); loadScript("http://cdn.bootcss.com/jquery/1.11.2/jquery.js",function(){document.getElementById("test").innerHTML+="jquery;"; }); loadScript("http://cdn.gbtags.com/jquery-color/2.1.2/jquery.color.min.js",function(){document.getElementById("test").innerHTML+="jq-color;"});loadScript("http://cdn.gbtags.com/jquery-easing/1.3/jquery.easing.min.js",function(){document.getElementById("test").innerHTML+="jq-easing;"});
那么结果正常情况下是:chart;jquery;jq-color;jq-easing; 你以为所有情况都是这种理想情况吗?too young ! too simple ! 假如加载速度都非常快的时候,或者js都存在缓存时候也许会这样!大多数情况下是这样的:
jquery;jq-color;jq-easing;chart;
或者jq-color;jq-easing;jquery;chart;等等可见顺序不是固定的,假如写在后面的easing.js又用到了前面jquery.js的内容,哇!肯定就会出现一系列的undefined错误,想想就可怕!那么!我们就必须在动态加载js的时候将异步变为同步!如下所示:newScripts是一个将要加载的script的顺序集合,采用迭代方法将他们依次加载,确保加载执行顺序:
var newScripts = ["http://cdn.bootcss.com/Chart.js/2.0.0-alpha3/Chart.js","http://cdn.bootcss.com/jquery/1.11.2/jquery.js","http://cdn.gbtags.com/jquery-color/2.1.2/jquery.color.min.js","http://cdn.gbtags.com/jquery-easing/1.3/jquery.easing.min.js"];//迭代加载,callback为全部加载完成后的回调函数(function scriptRecurse(count, callback) { if (count == newScripts.length) { callback && callback(); } else { loadScript(newScripts[count], function () { document.getElementById("test2").innerHTML+=newScripts[count]+";
"; scriptRecurse(++count, callback); }); }})(0);
网友评论