公众号:程序员波波
之前写了一篇异步引入的博客,但是在开发中遇到,可能某些js之间有调用关系,那么引入的时候就需要按照一定的顺序进行同步引入。
这里采用了递归的方式:
class Tools
{
static loadScript(url, callback)
{
let old_script = document.getElementById(url);
if (old_script)
{
if (old_script.ready == true)
{
// console.log("INFO:already load:" + url);
callback();
return;
}
else
{
document.body.removeChild(old_script);
// console.log("INFO:remove an old script that not ready:" + url);
}
}
let script = document.createElement('script');
script.id = url;
script.src = url;
script.onload = script.onreadystatechange = function() {
if (script.ready) {
return false;
}
if (!script.readyState //这是FF的判断语句,因为ff下没有readyState这个值,IE的readyState肯定有值
|| script.readyState == "loaded" || script.readyState == 'complete' // 这是IE的判断语句
) {
// console.log("INFO:load:" + url);
script.ready = true;
callback();
}
};
document.body.appendChild(script);
}
//synchronization
//同步加载多个脚本
static syncLoadScripts(scripts, callback)
{
var ok = 0;
var loadScript = function(url) {
Tools.loadScript(url, function(){
ok++;
// console.log("init:" + url)
if (ok == scripts.length) {
callback();
}
else {
loadScript(scripts[ok])
}
})
}
loadScript(scripts[0]);
}
//asynchronization
//异步加载多个脚本
static asyncLoadScripts(scripts, callback)
{
var ok = 0;
for (var i=0; i < scripts.length; i++) {
Tools.loadScript(scripts[i], function() {
console.log(scripts[ok])
ok++;
if (ok==scripts.length)
{
callback();
}
})
}
}
}
export default Tools;
对于加载大量js的时候,建议分批次加载,对于互相不影响的放在第一批进行异步加载,然后在回调中同步加载剩余有顺序的js。
或者分成一批完全不依赖顺序的开始异步加载,然后直接对于剩余有顺序要求的进行同步加载。