High-performance JavaScript note one (load and execute, data access, DOM programming)

Source: Internet
Author: User
Tags script tag

Write in front

Good book, perhaps you can not understand the first time the inside of the spirit, when again carefully evaluation, found that the understanding is a new layer of meaning

(This period of time, the work will not do as before, and began to have a new challenge, now the boss let me both admire and jealous, but really is the heart of admiration, hope that one day I can get to his height)

Now that it is not up to that level, make a good pile of bricks, when the brick pile to a certain height will naturally a small step.

Script Location

The script blocks page rendering until they are all downloaded and executed, and the page continues to render. The page only loads and executes the previous script external file to load the following script tag.

IE8, FireFox3.5, Safari4, and Chrome2 only started to allow parallel download of JavaScript files, which means that from this time the script tag does not block other script tags while downloading external resources, but The process of JavaScript download still blocks the download of other resources (slices), although the download process of the script does not interfere with each other, but the page still has to wait for all JavaScript code to be downloaded and executed to continue

This is why it is recommended that all script tags be placed at the bottom of the body tag as much as possible to minimize the impact on the entire page download

Organizing scripts

Because page rendering is blocked by the initial download of each script tag, reducing the number of script tags included in the page can improve page performance (not just for outer-chain scripts, but also for inline scripting)

Placing an inline script on a link tag that references an outer-chain style sheet causes the page to block to wait for the stylesheet to be downloaded, and the browser does so to ensure that the inline script gets the most accurate style information when it executes, so it is recommended never to immediately follow the inline script behind the link tag

Consolidate multiple files into one to reduce performance consumption

No blocking script

A non-blocking script that loads JavaScript code after the page has been loaded, there are several ways to implement

1. The script tag has an extended attribute Defer,defer property indicates that the scripts contained in this element do not modify the DOM, so the code can be safely deferred (but it is not compatible with all browsers)

The script tag with the defer attribute can be placed anywhere in the document, and the corresponding JavaScript file will start downloading when the page resolves to the script tag, but will not execute until the DOM is loaded (not just the outer chain script, but also the inline script)

That is, when a JavaScript file with the Defer property is downloaded, it does not block other browsers ' processes, so it can be downloaded in parallel with other resources on the page

2. Dynamic scripting elements: Because the script element is not materially different from the other elements of the page, using this, you can create a script with JS and add it to the page, the advantage is: whenever you start the download, the file download and execution process will not block the page other processes, You can even put the code in the head area of the page without affecting the rest of the page.

In general, adding a newly created script tag to the head tag is more insured than adding it to the body, especially if the code is executed during page loading, because the contents of the body are not fully loaded.

When you download a file using a dynamic script node, the returned code is usually executed immediately (there is also a problem, so you have to make sure that the interface you need to call in your code is ready)

The script element provides a ReadyState property, which has 5 kinds of values

    • Uninitialized initial state
    • Loading start Download
    • Loaded Download complete
    • Interactive data complete download but not yet available
    • Complete all data is ready
        /** @desc: Dynamic load Script * @param for all browsers: src * @param of URL script: Callback callback function*/        functionloadscript (URL, callback) {varScript = document.createelement (' script '); Script.type= ' Text/javascript '; if(script.readystate) {//IEScript.onreadystatechange =function () {                    //IE is inconsistent in identifying the value of the final state readystate, sometimes reaching the loaded state without reaching complete, and sometimes not even passing loaded to complete state,                    //so the way to do this is to check both of these states.                    if(script.readystate = ' Loaded ' | | script.readystate = = ' complete ') {Script.onreadystatechange=NULL;                    Callback (); }                }            } Else{script.onload=function() {callback (); }} script.src=URL; document.getElementsByTagName (' head ') [0].appendchild (script); }

The browser does not guarantee the order of execution by dynamically loading JS using the above code method

3, using XMLHttpRequest (XHR), that is, by creating a XHR through, and then use it to download the JS file, and finally dynamically create a script element to inject code into the page

        varXHR =NewXMLHttpRequest (); Xhr.open (' Get ', ' file1.js ',true); Xhr.onreadystatechange=function () {            if(Xhr.readystate = = 4) {                if(Xhr.status >= && Xhr.status < | | xhr.status = 304) {//2XX indicates a valid response of 304 to read from the cache                    varScript = document.createelement (' script '); Script.type= ' Text/javascript '; Script.text=Xhr.responsetext;                Document.body.appendChild (script); }}} xhr.send (NULL);

Features of using XHR:

    • Download JavaScript code, but do not immediately execute
    • The same code will work in all browsers.
    • The requested JS file must be the same domain as the requested page card
Recommended non-blocking mode
    <Script>        /** @desc: Dynamic load Script * @param for all browsers: src * @param of URL script: Callback callback function*/        functionloadscript (URL, callback) {varScript=Document.createelement ('Script'); Script.type= 'Text/javascript'; if(script.readystate) {//IEScript.onreadystatechange= function () {                    //IE is inconsistent in identifying the value of the final state readystate, sometimes reaching the loaded state without reaching complete, and sometimes not even passing loaded to complete state,                    //so the way to do this is to check both of these states.                    if(Script.readystate= 'Loaded' ||script.readystate== ' Complete') {Script.onreadystatechange= NULL;                    Callback (); }                }            } Else{script.onload= function() {callback (); }} script.src=URL; document.getElementsByTagName ('Head')[0].appendchild (script); }        //embed the Loadscript function directly into the page to avoid a single HTTP requestLoadscript ('Therest.js', function () {            //The rest of the code needed to load the initialization page            //Benefit 1) Ensure that the display of other contents of the page is not blocked during JS execution                //2) When the second JS file completes the download, all the DOM structures required by the application are created and ready for interaction, thus avoiding the need for another event        }); </Script>
View Code

You can get to know the Lazyload class library, which is a more general delay loading tool

Check out my other blog post Labjs (similar to Lazyload, but it's more convenient to manage dependencies)

Summarize deferred loading

Data access related performance optimization rules

Where data is stored is related to access speed

1. If a cross-scope value is referenced more than once in a function, store it in a local variable

2, there are two statements can be executed temporarily change the scope chain, one is with, one is catch (after a deep understanding of the scope chain will find that with all the properties of the object to re-create a variable and push it to the top of the scope, then the original object's properties are located in the second layer of the scope chain, This does not slow the access to local variables) avoid using the WITH statement

3, catch with the same principle, if the code is wrong, the execution process will automatically jump to the catch clause, and then push the exception object into a Mutable object and placed in the scope of the head, within the catch code block, the function of all local variables will be placed in the second scope chain object, A good pattern is to delegate the error to a function handler (the CATCH clause executes and the scope chain returns to its original state)

        Try {            methodmaycauseerror ();         Catch (ex) {            handlererror (ex); // delegate to processor method            // temporary changes to the scope chain do not affect code performance because only one statement is executed and there is no access to the local variable        }

4, both with, Try-catch, and Eval are considered dynamic scopes because dynamic scopes exist only during code execution. Therefore, it cannot be detected by static analysis. So it's recommended to use dynamic scopes only when it's really necessary.

5. Closures allow a function to access data outside the local scope, but it also raises memory performance issues (it is also possible to store common cross-scope variables in the same way as local variables).

6. The deeper the object exists in the prototype chain, the slower it is to find it. Similarly, the deeper the nesting of object members, the slower the access speed. This is why reading the same object property multiple times is best done by saving the property value in a local variable

(Object.name operation by dot notation and object[' name ' operation via bracket notation) In fact, there is no significant difference in performance, and the point symbol is always fast in safari only.

Summarize data access

DOM Programming

Because the internal mechanism of the browser is to implement the DOM and JavaScript independently, it also means that the two independent functions can only be connected to each other through the interface, resulting in consumption

The best way to modify the page area is to use innerHTML a little faster than the Document.createelement method.

Replacing the Document.createelement method with Element.clonenode is more efficient, but it's not particularly obvious.

        document.getelementsbyname ();        Document.getelementsbyclassname ();        document.getElementsByTagName ();        Document.images;        Document.links;        document.forms;        document.forms[0].elements;

The objects returned in the above code are HTML collection objects, which are in a real-time state, that is, it remains connected to the document, and each time you need the latest information, the process of executing the query repeats (even if you simply access the length property of the collection), It is also better to store the collection in a local variable when accessing the collection element, and to cache the length in the outer loop

        function ToArray (coll) {            for (var i = 0,a=[],len=coll.length; i < Len; i++) {                =
   
     > Coll[i];            }             
    return 
    A;        }
   

When looking for elements in the DOM, it is probably childnodes and nextsibling, but if your browser needs to be compatible with IE, it is recommended to use the NextSibling method to view DOM nodes

Dom properties such as ChildNodes, FirstChild, nextsibling do not differentiate between element nodes and other types of nodes, such as annotations and text nodes, and in many cases only the element nodes need to be accessed, so the type of the returned node needs to be checked and the non-element node filtered out in the loop. But these types of checks are unnecessary DOM operations, and using children instead of childnodes will be faster

If browsers have native Queryselectorall () methods and Queryselector () methods to use them as much as possible (because they need to write very much code to implement their functions), There is one common feature of any programming language is that native methods are always best-performing.

Rearrange and redraw

When DOM changes affect the geometric properties of an element, the browser needs to recalculate the geometry of the element, as well as the geometry properties and position of the other elements. The browser causes the affected parts of the render tree to get out of control and reconstructs the render tree, which is called reflow, and when the reflow is done, the browser redraws the affected part to the screen, which is called redraw

When does the rearrangement occur?

    • Add or remove a visible DOM element
    • Element position Change
    • Element size Change
    • Content changes
    • Page Browser Initialization
    • browser window size Change

It is important to note that accessing the following properties triggers a reflow (so it is best to avoid using the attributes listed above in the process of modifying the style)

Minimize reflow and redraw

Merge all the changes and then process it one at a time, so just modify the DOM once, 1) using the Csstext property to implement 2) modify the CSS class name to change

Cache layout information (such as offset offsets, scrolling position, or calculated style values Computedstyle values minimize the number of times the layout information is obtained, assign to local variables, and then manipulate local variables)

Use the following steps to reduce the number of reflow and redraw times

    1. Remove this element from the document stream
    2. Apply multiple changes to it
    3. Bring elements back to the document

There are three ways to get the DOM out of the document

    1. Hide an element, modify it, and then display it
    2. Use a document fragment to create a subtree outside of the saved Dom and then copy it to the document (this method is recommended because it involves a minimum number of DOM operations and rearrangement)
    3. Copy the original element to a node that is out of the document, modify the copy, and then overwrite the original element
 for(vari = 0; i < 1000; i++) {            varel = document.createelement (' P '); El.innerhtml=i;        Document.body.appendChild (EL); }        //can be replaced by:        varFrag =document.createdocumentfragment ();  for(vari = 0; i < 1000; i++) {            varel = document.createelement (' P '); El.innerhtml=i;        Frag.appendchild (EL); } document.body.appendChild (Frag);

if it is an animated element, it is best to use absolute positioning to keep it out of the flow of the document, so that changing its position does not cause the other elements of the page to Reflow (that is, if it is an animated element, it is best to use absolute positioning to leave it out of the document stream. Changing its position does not cause the other elements of the page to reflow, but it will only affect its own rearrangement. )

ie if you have a large number of elements used: hover, then it will slow down the response

DOM Programming Summary

High-performance JavaScript note one (load and execute, data access, DOM programming)

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.