按特定顺序加载多个脚本

时间:2018-06-06 22:27:04

标签: javascript typescript onload

我需要按特定顺序加载几个js脚本。事实上,我是在打字稿中做的,我不能使用jQuery,只能使用纯粹的ts / js。我现在拥有的是:

var script1 = document.createElement('script');
script1.type = 'text/javascript';
script1.src = 'script1.js';
document.head.appendChild(script1);
script1.onload = function () {

    var script2 = document.createElement('script');
    script2.type = 'text/javascript';
    script2.src = 'script2.js';
    document.head.appendChild(script2);
    script2.onload = function () {

        etc...

    }

}

它有效,但我相信还有更优雅的方法吗?请举例说明vanilla javascript或typescript。

2 个答案:

答案 0 :(得分:2)

是的!有。使用Promisesasync/await

function loadScript(url) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.src = url
    document.head.appendChild(script)
    script.onload = () => resolve()
  })
}

async function loadScripts() {
  await loadScript('script1.js')
  await loadScript('script2.js')
  // ..
}

loadScripts().then(_ => console.log('All scripts loaded in specified order'))

答案 1 :(得分:1)

更优雅的方式可能类似于下面的代码,您首先定义所有内容,但仍按上述顺序加载所有内容。这使用辅助函数来追加,然后设置下一个脚本的加载函数,并将脚本引用存储在一个数组中,以简化此操作。

/*
* Load the scripts in a specific order
*/
function loadScripts() {
    var scripts = [];
    var numScripts = 2
    for (let i=0; i<numScripts, i++) {
        scripts[i] = document.createElement('script');
        scripts[i].type = 'text/javascript';
        scripts[i].src = '"script"+i+".js"; //NOTE: if your scripts start on 1, not 0, you need "i+i"
    }
    loadScriptHelper(scripts,0);
}

/*
* Helper function for load scripts
*/
function loadScriptHelper(scripts,i) {
    document.head.appendChild(scripts[i]);
    scripts[i].onload = function() {
        loadScriptHelper(scripts,i+1);
    }
}