Preload script without execute

前端 未结 6 1869
生来不讨喜
生来不讨喜 2020-12-06 17:09

Problem

In order to improve the page performance I need to preload scripts that I will need to run on the bottom page.

I

6条回答
  •  半阙折子戏
    2020-12-06 17:30

    Why not to try this?

    var script = document.createElement('script');
    script.src = 'http://path/to/your/script.js';
    script.onload = function() {
      // do something here
    }
    
    document.head.appendChild(script);
    

    you can use .onload event to control when it is loaded. One caveat is that .onload() doesn't work in IE and you can use this:

    script.onreadystatechange = function() {
      if (/^loaded|complete$/i.test(this.readyState)) {
        // loaded
      };
    }
    

    Additionally adding scripts via DOM is non-blocking and i believe you can perfectly achieve your goals with this approach.

提交回复
热议问题