High-performance JavaScript Learning Note Series (1)-js Loading and execution

Source: Internet
Author: User

The content of this note mainly relates to JS script location, how to load JS script and script file execution problems, according to their own understanding combined with high-performance JavaScript organized

JavaScript is an explanatory code, the explanatory code needs to go through the process of translating into computer instructions, this process will bring some performance loss, so in JS to do performance optimization is necessary

JavaScript blocking feature: When the browser executes the JS code, it cannot do anything else, because the browser uses a single process to handle the user interface refresh and JavaScript script execution, that is, when the execution of the JS script affects the user's experience with the page ( The reason JS will block the parsing and rendering of the page, because it is not possible to expect JS when the page will be modified, so will first execute the JS code in the continuation of parsing and rendering interface, whether it is the external chain of JS files or inline JS file.

Based on the above reasons, JS file location determines the user's experience and through the optimization of JS file to maximize the performance of the page

<Head>  <MetaCharSet= "UTF-8">  <title>Document</title>  <Scripttype= "Text/javascript"src= "A.js"></Script>  <Scripttype= "Text/javascript"src= "B.js"></Script>  <Linkrel= "stylesheet"type= "Text/css"href= "Style.css" /></Head>

Above this mode we put the JS file in the head, such a position is problematic

(1) The first JS blocking feature will cause the need to wait for these two files to download and execute, the page will be rendered, there will be blank, the user experience is not good

(2) The browser does not render any part of the page before parsing the body tag, that is, the a.js and b.js do not exist in the process of the page Dom tree, this time the page operation will be error

/* Although the modern browser can realize the parallel download of JS, but JS download process will block the download of other resources, such as the CSS file chain is already parallel download * *

So the recommended location for JS script placement is the following form

<Body><Scripttype= "Text/javascript"src= "A.js"></Script><Scripttype= "Text/javascript"src= "B.js"></Script></Body>

This placement mode when downloading script files and executing script files, most of the content of the page has been displayed to the user, that is, placed at the bottom of the body

Organizing scripts

Script tags will block the rendering of the page, from the perspective of improving the performance of the page, is how to reduce the script as much as possible to organize scripts, because the JS file is now more modular and functional, the number of files sometimes difficult to reduce the actual, a not particularly good plan, It is simple to merge two JS files, because reducing the HTTP request is faster than simply downloading two independent JS files, but there are some problems

(1) destroyed the JS file module, two different functions of the module was mixed together

(2) On the service side we need to add more JS files, occupy the resources of the server

We can implement a URL to load two JS files by using some static packaging tools or a merge processor like Yahoo provides via their CDN

/* Do not put inline script behind the outer chain style sheet, which will cause the page to block to wait for the stylesheet to download (in order to get the most accurate style information when the JS file executes) */

No blocking script

Through the above merge URL or merge JS file does not improve the performance of the page, so the non-blocking script, that is, after the page loading is completed before the JS code, that is, after the corresponding Window.onload event triggered to download the script ( A careful understanding of the non-blocking script is that this JS file download does not block the download of other elements of the page) there are several ways to achieve the above requirements

(1) Time-lapse script defer

Defer property in the JS file will not be modified when the document can be used, because the JS file does not modify the document, you do not have to wait for the execution of JS to stop the page rendering wait for the page to complete after the execution (no location requirements)

ANSYC attribute js file download completes automatically (body bottom download executes when the element of the page is ready to complete)

Non-blocking scripting can be implemented in both of these ways

Give an example of a defer

/* I have tested both chrome and IE support the defer property but when the JS file is inline, the defer will fail */

<Body><Scripttype= "Text/javascript"src= "A.js"defer></Script><Scripttype= "Text/javascript"defer>Console.log (1);</Script><inputtype= "button"value= "Test"ID= "BTN" /></Body>

The contents of the A.js are as follows

var btn = document.getElementById ("btn"); Console.log (BTN);

By looking at the console we found that A.js did delay execution, that is, the A.js file was executed before the page window.load but the inline JS file was not delayed

(2) The dynamic script element script element, like other elements, can dynamically create a script element, and this way the file download and execution process does not block other processes, and the script files added in this way are executed as soon as the download is complete. But when you add this script is a script to provide the interface, you need to obtain some information to confirm whether the current interface can then be carried out after the operation of IE can pass the onreadystatechange event To get the status of the script when it is completed through the ReadyState State Standard browser is the OnLoad event to determine the state of the added JS file

The following function can be used to implement the dynamic loading JS file

  functionLoadscript (url,callback) {varScript = document.createelement ("Script"); Script.type= "Text/javascript"; if(script.readystate) {Script.onreadystatechange=function(){            if(Script.readystate = = "Loaded" | | script.readystate = = "complete") {Script.onreadystatechange=NULL;                Callback (); }        }      } Else{window.onload=function() {callback (); }} script.src=URL; document.getElementsByTagName ("Head") [0].appendchild (script);/*when added to the page, the download is started and the process execution does not block other processes*/Console.log (1/*1 will output before the newly added script executes */}

If you need to download between scripts in a specific order, you can load the JS file in a callback way

  Loadscript ("a.js",function() {      loadscript ("b.js",function() {});  });

(3) The advantage of XMLHttpRequest script injection , which is to download the script file through the Xhr object, is that you can download the code but not execute it immediately, and then execute the code when you're ready.

  varXHR =NewXMLHttpRequest (); Xhr.open ("Get", "A.js",true);/*true to indicate asynchronous*/Xhr.onreadystatechange=function(){      if(Xhr.readystate = = 4) {        if(Xhr.status >= && Xhr.status < | | xhr.status = 304) {            varScript = document.createelement ("Script"); Script.type= "Text/javascript"; Script.text=Xhr.responsetext;        Document.body.appendChild (script); }}} xhr.send (NULL);

recommended way: load a small amount of code in a blocking manner, such as loadsript and then dynamically load the remaining code

<script type= "Text/javascript" src= "load.js" ></script><script type= "Text/javascript" >   Loadscript ("b.js",function() {    Console.log ("OK");  }); </script>

Reference high-performance JavaScript

High-performance JavaScript Learning Note Series (1)-js Loading and execution

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.