9

在脚本实际附加到文档之前,如何让回调不运行?

function addScript(filepath, callback){
    if (filepath) {
        var fileref = document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filepath);
        if (typeof fileref!="undefined")
            document.getElementsByTagName("head")[0].appendChild(fileref);
    }
    if (callback) {
        callback();
    }
}
4

4 回答 4

14

在理想世界中,您可以使用标签的onload属性;<script />

function addScript(filepath, callback){
    if (filepath) {
        var fileref = document.createElement('script');

        fileref.onload = callback;

        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filepath);

        if (typeof fileref!="undefined")
            document.getElementsByTagName("head")[0].appendChild(fileref);
    }
}

但是,这在 IE 中不起作用,因此需要 mega-h4x;

  function addScript(filepath, callback) {
      if (filepath) {
          var fileref = document.createElement('script');
          var done = false;
          var head = document.getElementsByTagName("head")[0];

          fileref.onload = fileref.onreadystatechange = function () {
              if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
                  done = true;

                  callback();

                  // Handle memory leak in IE
                  fileref.onload = fileref.onreadystatechange = null;
                  if (head && fileref.parentNode) {
                      head.removeChild(fileref);
                  }
              }
          };

          fileref.setAttribute("type", "text/javascript");
          fileref.setAttribute("src", filepath);

          head.appendChild(fileref);
      }
  }

FWIW,你if (typeof fileref != "undefined")是多余的,因为它总是评估为真,所以你可以直接做head.appendChild(fileref);,就像我的例子一样。

于 2013-05-24T21:24:57.030 回答
2

关于什么:

var myParticularCallback = function () {
    // do something neat ...
}

..... your code  

var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");

fileref.onload = myParticularCallback;

if (typeof fileref!="undefined")
    document.getElementsByTagName("head")[0].appendChild(fileref);

 // after all has set, laod the script and wait for onload event:
fileref.setAttribute("src", filepath);
于 2013-05-24T21:25:54.507 回答
1

这个小脚本/ css 加载器将完成这项工作 https://github.com/rgrove/lazyload/

LazyLoad.js('/foo.js', function () {
  alert('foo.js has been loaded');
});
于 2013-05-24T21:21:25.987 回答
-1

最简单的方法是定义一些可见callback()的函数,这些函数将在你动态包含的脚本中运行,最后。

于 2013-05-24T21:20:32.393 回答