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

问题描述:

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

How can I get the callback to not run until the script is actually appended to the document?

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();
    }
}


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

In the ideal world, you could use the onload property of the <script /> tag;

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;

However, this doesn't work in IE, so mega-h4x are required;

  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)是多余的,因为它总是评估为true,所以你可以做 head.appendChild(fileref); 直接,如我的例子。

FWIW, your if (typeof fileref != "undefined") was redundant, as it will always evaluate to true, so you can just do head.appendChild(fileref); directly, as in my example.