延迟回调,直到脚本添加到文档?

时间:2013-05-24 21:16:43

标签: javascript

如果在脚本实际附加到文档之前,如何才能使回调无法运行?

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 个答案:

答案 0 :(得分: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);
    }
}

然而,this doesn't work in 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);,如我的示例所示。

答案 1 :(得分: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);

答案 2 :(得分:1)

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

LazyLoad.js('/foo.js', function () {
  alert('foo.js has been loaded');
});

答案 3 :(得分:-1)

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