Load javascript async, then check DOM loaded before executing callback

前端 未结 2 394
离开以前
离开以前 2020-12-03 15:14

Problem:
Load js files asynchronously, then check to see if the dom is loaded before the callback from loading the files is executed.

2条回答
  •  眼角桃花
    2020-12-03 16:05

    What you need is a simple queue of onload functions. Also please avoid browser sniffing as it is unstable and not future proof. For full source code see the [Demo]

    var onload_queue = [];
    var dom_loaded = false;
    
    function loadScriptAsync(src, callback) {
      var script = document.createElement('script'); 
      script.type = "text/javascript";
      script.async = true;
      script.src = src;
      script.onload = script.onreadystatechange = function() {
        if (dom_loaded) 
          callback();
        else 
          onload_queue.push(callback);
        // clean up for IE and Opera
        script.onload = null;
        script.onreadystatechange = null;
      };
      var head = document.getElementsByTagName('head')[0];
      head.appendChild(script);
    }
    
    function domLoaded() {
       dom_loaded = true;
       var len = onload_queue.length;
       for (var i = 0; i < len; i++) {
         onload_queue[i]();
       }
       onload_queue = null;
    };
    
    // Dean's dom:loaded code goes here
    // do stuff
    domLoaded();
    

    Test usage

    loadScriptAsync(
      "http://code.jquery.com/jquery-1.4.4.js", 
      function() {
          alert("script has been loaded");
       }
    );
    

提交回复
热议问题