Implement high performance JavaScript implementation and load _ basics

Source: Internet
Author: User
Tags script tag

The browser handles HTML page rendering and JavaScript script execution in a single process, so when the browser encounters the <script> tag in the render HTML, it executes the code inside the tag (if it is a chain file loaded with the SRC attribute, it is downloaded and executed first). , page rendering and interaction will be blocked during this process.

... There are a few tricks to reduce the effect of JavaScript on performance, although there will be blocking.

Position of 1.script label

When <script> appears in

 
 

This load of multiple JS files, the browser will be downloaded after the implementation of JS code and blocking page rendering to appear white screen (browser parsing to <body> tags, will not render any content of the page), can not preview the interactive, very poor user experience.

Attention:

Modern browser support resources in parallel downloads, only limited to <script> download external resources will not block other <script> tags, but will block other resources download.
Downloading JavaScript resources is asynchronous, but executing JavaScript code is still synchronized, which can also cause blocking.
So put the <script> back to the bottom of the <body> tag, to ensure that the script has completed the page rendering before, is a more commonly used JavaScript optimization method.

2. Merging multiple script tags

Browser parsing HTML encountered <script> will be due to the execution of the script has a certain delay, for the SRC attribute of the chain is <script> more, multiple HTTP requests will bring more performance overhead, minimize this delay, but also an optimization means, Multiple JS files can be merged to reduce the number of HTTP requests, reduce the number of handshake three times and redundant HTTP header transmission, reduce response time to improve the user experience. There are many schemes and tools for merging JS on the Internet, which are not described here.

3. Using a non-blocking download JavaScript method

    1. Use the defer and async properties of the script label
    2. Use dynamically created script tags to download the execution JavaScript code
    3. Download JavaScript code using the XHR object and inject it into the page

3.1. Use the defer and async properties of the script tag

Async and Defer properties are used to load the JS file asynchronously, the period will not be blocked browser other processes, the difference is that async is loaded after the automatic execution, and defer need to wait until the page is loaded and then executed, it should be noted that these two properties must be in the SRC attribute of the < Script> label (outside the chain script) is valid. Here is the demo:

 <! DOCTYPE html> 

Only alert ("defer") is under the Defer.js file, and one line of code
Async example is also the same page structure, here is not an example, you can poke the link below.
Defer example's link stamp here!
Async Example's link stamp here!

Although the page structure is the same, but not the same

Open defer.html in turn see: Pop-up "script" alert box => page rendering out text => pop-up "defer" Alert box => pop-up "load" alert box
Open async.html in turn see: Pop-up "script" alert box => pop-up "async" alert box => page rendering text => pop-up "load" alert box

3.2. Use dynamically created script tags to download the execution 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, with the advantage that file.js downloads and executions do not block other processes on the page.

It is obvious from the demo that dynamic loading can see the text on the page before the alert box pops up, but the normal way is to see the text on the page only after the alert box pops up.

We can encapsulate a cross browser function that reads script scripts and dynamically creates script tags:

function Loadscript (url,callback) {
  var script = document.createelement ("script");
  Script.type = "Text/javascript";
  Detect client Type
  if (script.readystate) {//ie
    script.onreadystatechange = function () {
      if (script.readystate=== "Loaded" | | script.readystate=== "complete") {
        script.onreadystatechange = null;
        Callback ();}}
  else{//other browsers
    script.onload = function () {
      callback ();
    }  
  }
  
  script.src = URL;
  document.getElementsByTagName ("Head") [0].appendchild (script);
}

This kind of dynamic loading script's method compatibility is good, is also simpler, is a common non-blocking solution.

3.3. Use the Xhr object to download JavaScript code and inject the page

Another way to load a script without blocking is to use the XMLHttpRequest (XHR) object to get the script and inject it into the page.
This technique creates a Xhr object first, then downloads the JavaScript file with him, and finally injects the code into the page through a common dynamic <script> element.

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 detects whether readystate is 4 (4 for Request completion) and HTTP status valid (200 for a valid response, 304 for read cache). After judging the response, dynamically create a <script> tag, which is the responsetext received by the server.

Advantages and disadvantages of this approach:

Benefits: Downloading JavaScript code can be done without immediate, and compatibility is good for all major browsers.
Disadvantage: JavaScript files must be in the same domain as the requested page, in which case JavaScript files cannot be downloaded from CDN and are not suitable for large web applications.

4. A recommended non-blocking scheme

If the page has a large number of JavaScript code to add, you can first go outside the chain in the page we encapsulated the dynamic Read script function Loadscript, and then use it to load other required scripts, such as:

<script type= "Text/javascript" src= "loader.js" ></script>
<script type= "Text/javascript" >
  loadscript ("File.js", function () {
    //do something
  });
</script>

This will only have a slight effect on the page when the first <script> download the more streamlined loader.js files, and then <script> won't have much impact.

Related Article

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.