动态加载Javascript以及如何检查脚本是否存在

Lx1*_*Lx1 14 javascript

我正在使用以下技术动态加载Javascript:

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "file.js";
document.body.appendChild(script);
Run Code Online (Sandbox Code Playgroud)

这是一种非常常见的方法.它也在这里讨论:http://www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/

我知道如何在文件加载和执行后收到通知

我不知道的是,如果Javascript源文件的链接被破坏,我该如何得到通知.

谢谢

Dan*_*llo 22

在脚本元素上侦听事件不被认为是可靠的(来源).想到的一个选项是用于setTimeout()轮询您希望在外部脚本中定义的变量.之后x秒钟,你可以超时的调查,并考虑脚本打破.

外部脚本:file.js:

var MyLibrary = { };
Run Code Online (Sandbox Code Playgroud)

主要文件:

var poll;
var timeout = 100; // 10 seconds timeout
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'file.js';
document.body.appendChild(script);

poll = function () {
  setTimeout(function () {
    timeout--;
    if (typeof MyLibrary !== 'undefined') {
      // External file loaded
    }
    else if (timeout > 0) {
      poll();
    }
    else {
      // External library failed to load
    }
  }, 100);
};

poll();
Run Code Online (Sandbox Code Playgroud)