在执行其他内容之前,将脚本动态加载到文件顶部

时间:2019-05-17 13:43:05

标签: javascript html5

在加载外部脚本文件后,我必须根据情况在页面中加载剩余的代码行。

if(condtion){
var script = document.createEement("script")
script.type = "text/javascript";
script.src = "****";
document.getEementsByTagName("body")[0].appendChid(script);
afterLoad(callback)
}else{
callback();
}

function callback(){
//remaining lines to execute
}

1 个答案:

答案 0 :(得分:0)

您可以使用onload plus promise异步加载脚本。这里是一个例子:

function loadScript(src) {
  return new Promise(function(resolve, reject) {
    const s = document.createElement('script');
    let r = false;
    s.type = 'text/javascript';
    s.src = src;
    s.async = true;
    s.onerror = function(err) {
      reject(err, s);
    };
    s.onload = s.onreadystatechange = function() {
      // console.log(this.readyState); // uncomment this line to see which ready states are called.
      if (!r && (!this.readyState || this.readyState == 'complete')) {
        r = true;
        resolve();
      }
    };
    const t = document.getElementsByTagName('script')[0];
    t.parentElement.insertBefore(s, t);
  });
}

此代码是从https://gist.github.com/james2doyle/28a59f8692cec6f334773007b31a1523复制的