Home >Web Front-end >JS Tutorial >Summary of common ways to load JavaScript script files in html

Summary of common ways to load JavaScript script files in html

伊谢尔伦
伊谢尔伦Original
2017-07-21 16:08:191604browse

When the browser encounters the (embedded) 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag, the current browser has no way of knowing whether JavaScript will modify the page content. Therefore, the browser will stop processing the page at this time, first execute the javaScript code, and then continue to parse and render the page. The same situation also occurs in the process of using the src attribute to add javaScript (that is, external link javaScript). The browser must first spend time downloading the code in the external link file, and then parse and execute it. During this process, page rendering and user interaction are completely blocked.

In other words: whenever the browser parses the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag (whether embedded or external link), the browser will (singlely) prioritize downloading and parsing And execute the javaScript code in the tag, blocking the download and rendering of all subsequent page content.

Method 1: Conventional approach

The most traditional way is to insert 3f1c4e4b6b16bbbd69b2ee476dc4f83a in the head tag Label.

However, this conventional approach hides serious performance problems. According to the above description of the characteristics of the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag, we know that in this example, when the browser parses the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag, the browser will stop parsing the content after it, and give priority to downloading the script file and executing it. The code in it means that the subsequent test.css style file and the 6c04bd5ca3fcae76e30b72ad730ca86d tag cannot be loaded. Since the 6c04bd5ca3fcae76e30b72ad730ca86d tag cannot be loaded, the page cannot be rendered. Therefore, the page will be blank until the javaScript code is completely executed.

<script type="text/javaScript" src="example.js"></script>

Method 2: Classic approach

##Since the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag will block the loading of subsequent content , then wouldn’t it be possible to avoid this bad situation by placing the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag after all page content? Place all 3f1c4e4b6b16bbbd69b2ee476dc4f83a tags as close to the bottom of the 6c04bd5ca3fcae76e30b72ad730ca86d tag as possible to minimize impact on the download of the rest of the page.

Parallel downloading of scripts has been implemented on IE8+ browsers, but in some browsers (even if the script file is placed at the bottom of the 6c04bd5ca3fcae76e30b72ad730ca86d tag), the scripts in the page are still loaded one after another. So we need the next method, which is: dynamically loading scripts.

Method 3: Dynamic script

Through the Document Object Model (DOM), we can almost anywhere on the page create.

##

<script type=&#39;text/javascript&#39;>
  var script = document.createElement(&#39;script&#39;);
  script.type = &#39;text/javaScript&#39;;
  script.src = &#39;file1.js&#39;;
  document.getElementsByTagName(&#39;head&#39;)[0].appendChild(script);
</script>

The above code dynamically creates a 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag of external link file1 and adds it to the 93f0f5c25f18dab9d176bd4f6de5d30e tag. The key point of this technology is:

No matter when the download is started, the download and execution process of the file will not block other processes on the page (including script loading).

However, this method is also flawed. The script loaded by this method will be executed immediately after the download is completed, which means that the running order between multiple scripts cannot be guaranteed (except for Firefox and Opera). When a script has a dependency on another script, errors are likely to occur. For example, to write a jQuery code, you need to import the jQuery library. However, the jQuery code file you write will most likely be downloaded first and executed immediately. At this time, the browser will report an error - 'jQuery is not defined' or the like, because jQuery is not defined at this time. The library has not been downloaded yet. So the following improvements were made:


<script type=&#39;text/javascript&#39;>
  function loadScript(url, callback) {
    var script = document.createElement(&#39;script&#39;);
    script.type = "text/javaScript";
    // IE和opera支持onreadystatechange
    // safari、chrome、opera支持onload
    if (script.readyState) {//IE
      script.onreadystatechange = function() {
        if (script.readyState == "loaded"
            || script.readyState == "complete") {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else {//其他浏览器
      script.onload = function() {
        callback();
      };
    }
    script.src = url;
    document.getElementsByTagName(&#39;head&#39;)[0].appendChild(script);
  }
</script>

The improvement in the above code is to add a callback function, which will be called after the corresponding script file is loaded. In this way, sequential loading can be achieved. The writing is as follows (assuming that file2 depends on file1, and file1 and file3 are independent of each other):

loadScript(‘file1.js&#39;,function(){ loadScript(‘file2.js&#39;,function(){}); }); loadScript(‘file3.js&#39;,function(){});

file2 will start loading after file1 is loaded, ensuring that file1 has been prepared before file2 is executed. appropriate. File1 and file3 are downloaded in parallel and do not affect each other. Although the loadScript function is good enough, there are still some unsatisfactory aspects - by analyzing this code, we know that the sequential loading in the loadScript function is implemented by blocking loading of the script (as pointed out in the red text above) . What we really want to achieve is - the scripts are downloaded synchronously and executed in the corresponding order, that is, loaded in parallel and executed sequentially.

The above is the detailed content of Summary of common ways to load JavaScript script files in html. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn