繁体   English   中英

如何延迟运行某些JS代码,直到下载所有异步JS文件?

[英]How can I delay running some JS code until ALL of my asynchronous JS files downloaded?

更新

我有以下代码:

<script type="text/javascript">
function addScript(url) {
    var script = document.createElement('script');
    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
}   
addScript('http://google.com/google-maps.js');
addScript('http://jquery.com/jquery.js');

...

// run code below this point once both google-maps.js & jquery.js has been downloaded and excuted

</script>

在下载并执行所有必需的JS之前,如何防止代码执行? 在上面的示例中,这些必需文件是google-maps.js和jquery.js。

您可以将脚本元素的onload事件用于大多数浏览器,并使用回调参数:

编辑:以这种方式加载脚本时,您不能真正停止执行代码(并且在大多数情况下发出同步Ajax请求是一个坏主意)。

但是您可以链接回调,因此,如果您有一些代码依赖Two.jsThree.js ,则可以链接加载操作,例如:

loadScript('http://example.com/Two.js', function () {
  // Two.js is already loaded here, get Three.js...
  loadScript('http://example.com/Three.js', function () {
    // Both, Two.js and Three.js loaded...
    // you can place dependent code here...
  });
});

实现方式:

function loadScript(url, callback) {
  var head = document.getElementsByTagName("head")[0],
      script = document.createElement("script"),
      done = false;

  script.src = url;

  // Attach event handlers for all browsers
  script.onload = script.onreadystatechange = function(){
    if ( !done && (!this.readyState || // IE stuff...
      this.readyState == "loaded" || this.readyState == "complete") ) {
      done = true;
      callback(); // execute callback function

      // Prevent memory leaks in IE
      script.onload = script.onreadystatechange = null;
      head.removeChild( script );
    }
  };
  head.appendChild(script);
}

对于IE,必须绑定onreadystatechange事件。

我刚刚阅读了CMS的答案 ,并决定从他的“大多数浏览器”评论中,我可能会想尽办法使它本身不具有此功能的人能够使用。

基本上,这是一个轮询变量的时间间隔。

var poll = window.setInterval(function() {

    if (typeof myVar !== 'undefined') {
        clearInterval(poll);
        doSomething();
    };

}, 100);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM