High-performance JavaScript Execution and loading; high-performance javascript

Source: Internet
Author: User

High-performance JavaScript Execution and loading; high-performance javascript

The browser processes HTML page rendering and JavaScript script execution in a single process, therefore, when the browser encounters the <script> tag during HTML Rendering, the code in the tag is executed first (if the code is an external link file loaded using the src attribute, the code is downloaded before execution ), in this process, page rendering and interaction are blocked.

... Although there will be blocking, there are still a few moves to reduce the impact of JavaScript on performance.

1. script tag location

When <script> appears in

When loading multiple js files, the browser will block page rendering by downloading and executing the js Code first to display a white page (before the browser parses the <body> label, does not render any page content), cannot preview or interact, very poor user experience.

Note:

Modern browsers support parallel resource download. Only when downloading external resources by <script>, other <script> tags are not blocked, but download of other resources is blocked.
Downloading JavaScript resources is asynchronous, but the JavaScript code is still synchronized, which also causes blocking.
Therefore, the <script> is placed at the bottom of the <body> label to ensure that page rendering has been completed before the script is executed. This is a common JavaScript optimization method.

2. Merge multiple script tags

When parsing HTML in a browser, <script> may delay execution of the script. For external links with the src attribute, <script>, multiple HTTP requests bring more performance overhead. It is also an optimization method to minimize this latency. Multiple js files can be merged to reduce the number of HTTP requests, reduce the number of three handshakes and excessive HTTP header transmission, and reduce the response time to improve user experience. There are many js merge solutions and tools on the Internet, which are not described here.

3. Use the method of downloading JavaScript without blocking

  1. Use the defer and async attributes of the script tag
  2. Use the dynamically created script tag to download and execute JavaScript code
  3. Use the XHR object to download JavaScript code and inject the page

3. 1. Use the defer and async attributes of the script tag

The async and defer attributes are used to asynchronously load js files. During this period, other browser processes are not blocked. The difference is that async is automatically executed after loading, and defer needs to wait until the page is loaded before executing, note that these two attributes must be in the <script> label (external link script) of the src attribute. The following is a demo:

<!DOCTYPE html>

// Only alert ("defer") in the defer. js file; one line of code
The async example also has the same page structure. Here we will not describe the example. You can stamp the following link.
The link of defer example is here!
The link stamp of async example is here!

Although the page structure is the same, the difference is that

When you open defer.html, you can see that the "script" alert box is displayed. The "defer" alert box is displayed. The "load" alert box is displayed.
Open async.html and click "script"'s alert box => "async"'s alert box => text rendered on the page => load "'s alert box

. Use the dynamically created script tag to download and execute JavaScript code

var script = document.createElement("script");script.type = "text/javascript";script.src = "file.js";document.getElementByTagName("head")[0].appendChild(script);

File. js starts the download when the script element is added to the page. The advantage of this method is that the download and execution of file. js does not block other processes on the page.

From the demo, we can see that the dynamic loading mode can be seen before the alert box pops up, however, the text on the page can be seen only after the alert box is displayed.

We can encapsulate a function that can read a script across browsers and dynamically create a script Tag:

Function loadScript (url, callback) {var script = document. createElement ("script"); script. type = "text/javascript"; // check the client type if (script. readyState) {// IE script. onreadystatechange = function () {if (script. readyState = "loaded" | script. readyState = "complete") {script. onreadystatechange = null; callback () ;}} else {// other browser scripts. onload = function () {callback () ;}} script. src = url; document. getElementsByTagName ("head") [0]. appendChild (script );}

This kind of dynamic loading script has good compatibility and simplicity, and is a common non-blocking solution.

3. Use the XHR object to download JavaScript code and inject the page

Another way to load scripts without blocking is to use the XMLHttpRequest (XHR) object to get the script and inject it into the page.
This technology will first create an XHR object, then use it to download JavaScript files, and finally inject code into the page through common dynamic <script> elements.

var xhr = new XMLHttpRequest();xhr.open("get","file.js",true);xhr.onreadystatechange = function(){  if(xhr.readyState===4){    if(xhr.status>=200&&xhr.status<300||xhr.status==304){      var script = document.createElement("script");      script.type = "text/javascript";      script.text = xhr.responseText;      document.body.appendChild(script);    }  }}

The above code sends a GET request file. js file. onReadyStateChange checks whether the readyState is 4 (4 indicates the request is completed) and the HTTP status is valid (200 indicates a valid response, and 304 indicates reading the cache ). After the response is determined to be valid, a <script> tag is dynamically created. The content is the responseText received by the server.

Advantages and disadvantages of this method:

Advantage: JavaScript code can be downloaded without immediate execution, and the compatibility is suitable for all mainstream browsers.
Disadvantage: JavaScript files must be in the same domain as the requested page. In this case, JavaScript files cannot be downloaded from CDN and are not suitable for large Web applications.

4. A recommended non-blocking solution

If you need to add a large number of JavaScript code on the page, you can encapsulate the loadScript function for dynamically reading the script before removing the external link in the page, and then use it to load other required scripts, for example:

<script type="text/javascript" src="loader.js"></script><script type="text/javascript">  loadScript("file.js",function(){    //do something  });</script>

In this way, you only need to have a slight impact on the page when downloading the streamlined loader. js file in the first <script>, and the subsequent <script> will not have much impact.

Articles you may be interested in:
  • How to execute js after page loading is complete
  • Multiple methods to execute a js function after the jsp page is fully loaded
  • After the page is loaded, execute the jquery Writing Method of JS and the difference
  • Automatically execute the js Code of a method after the page is loaded.
  • Run the code after the JS implementation document is loaded.
  • Analysis of JavaScript script loading and execution in browser environment: defer and async features

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.