JavaScript performance optimization (i)

Source: Internet
Author: User
Tags script tag

First, load

1. Script tags can be placed anywhere in the head and body tags according to the HTML 4 specification

2. Download JS script will block other page file download, so you should place the script tag at the bottom of the body whenever possible

3. HTML 4 Adds a defer attribute to the script tag indicating deferred execution, but this is not a standard practice

4. Merging multiple script to compress, placed at the bottom of the body tag, is a best practice to introduce multiple out-chain JavaScript files

5. By dynamically creating tags, JS files can be introduced asynchronously, the code is as follows:

1 functionloadscript (URL, callback) {2     3     varScript = document.createelement (' script ')4Script.type = ' Text/javascript '5 6     //IE7     if(script.readystate) {8Script.onreadystatechange =function() {9             if(Script.readystate = = ' Loaded ' | | script.readystate = = ' complete ') {TenScript.onreadystatechange =NULL One Callback () A             } -         } -  the     //Other browser -}Else { -Script.onload =function() { - Callback () +         } -     } +  ASCRIPT.SRC =URL atDocument.getelementbytagname (' head ') [0].appendchild (script) -}

6. Using the XHR object, you can also introduce JS asynchronously. Unlike the above, you can get accurate loading progress, and the script does not run as soon as it is loaded (depending on when the script tag is added to the page)

1 varXHR =NewXMLHttpRequest ()2 3Xhr.open (' Get ', ' file.js ',true)4Xhr.onreadystatechange =function() {5 6     if(Xhr.readystate = = 4) {7         if(Xhr.status >= && Xhr.status < | | xhr.status = 304) {8 9             varScript = document.createelement (' script ')Ten  OneScript.type = ' Text/javascript ' AScript.text =Xhr.responsetext -  - document.body.appendChild (script) the         } -     } -}

Second, the data

1. JavaScript Data type: Direct volume, variable, array, object

2. Direct and local variables are accessed faster than array items and object members, and variable access performance is directly related to scope nesting

3. Closure ratio non-closure function requires more memory overhead (the lifetime of the variable is extended and not necessarily released at the end)

4. Use hasOwnProperty to find only the instance, and use for in to iterate over the object members to access the prototype

5. Each time the "." Operator is used, it causes the JavaScript engine to search all object members, the deeper the object is nested, and the slower it becomes. Especially when accessing the properties (methods) in the prototype chain

6. Using the "." Operator, it will be faster than [key] under Safari, but [key] is more general (the property is reserved word)

7. Namespaces are one of the causes of frequent access to nested properties, and caching of namespaces can effectively reduce the number of object accesses

  

1 // Caching a namespace 2 var load = ME.core.load34//  Cache resource.length to avoid accessing resource5 for each traversal (var i = 0, length = resource.length ; i < length; i++) {67    load. LoadResource (Resource[i].url)8 }

Third, DOM

1. The Document Object Model (DOM) is a language-independent application interface for manipulating XML and HTML documents

2. Dom and ECMAScript are two separate functions that consume when they access each other through the interface. Access to DOM elements to be charged "toll", the modification of elements is more expensive, because it will cause the browser to recalculate the geometric changes of the page

3. Using DOM to generate HTML (body.appendchild) is roughly the same as using innerHTML efficiency, innerHTML better on older browsers

4. On most browsers, the Clone node (CloneNode) is more efficient than the build node (createelement)

5. The HTML collection remains linked to the document, and each time it is accessed, the query is repeated, even if only the number of elements in the collection is obtained. The following methods and properties can cause this inefficient situation

1 Document.getelementsbyname () 2 Document.getelementsbyclassname () 3 document.getElementsByTagName () 4 5 document.images 6 document.forms 7 document.links 8 document.forms[0].elements

6. Traversing element sub-nodes, ie using nextsibling faster than childnodes

1 //nextSibling2 functiontestnextsibling () {3     varel = document.getElementById (' father '),4CH =El.firstchild,5Name = ' '6 7      Do {8Name =Ch.nodename9 Ten} while(ch =ch.nextsibling) One  A     returnname - } -  the //ChildNodes - functiontestchildnodes () { -     varel = document.getElementById (' father '), -CH =El.childnodes, +Len =Ch.length, -Name = ' ' +  A      for(vari = 0; i < Len; i++) { atName =Ch[i].nodename -     } -  -     returnname -}

7. Using native Queryselector and queryselectorall will achieve better efficiency than traversal (ie8+)

8. When DOM changes affect geometric attributes (box models), the geometry properties and locations of other elements are also affected (normal flow). The browser invalidates the affected portions of the rendered tree and reconstructs the rendering trees. This process is called "reflow". When the reflow is complete, the browser redraws the affected section to the screen, which is called redrawing. Reflow occurs in the following situations:

    • Add or remove a visible DOM element
    • Element position Change
    • Element box model change (padding, margin, width, height, border)
    • Content changes, such as text or picture paths
    • Page Renderer Initialization
    • browser window size Change

Some changes trigger the rearrangement of the entire page, for example, when the scroll bar appears

9. Reflow results in computational consumption, and most browsers optimize the reflow process through queued modification and batch execution. Getting layout information can result in queued flushing, such as the following methods:

    • Offsettop,offsetleft,offsetwidth,offsetheight
    • Scrolltop,scrollleft,scrollwidth,scrollheight
    • Clienttop,clientleft,clientwidth,clientheight
    • getComputedStyle ()

It is best to avoid using the above attributes while modifying styles

10. The consolidation of multiple changes into a single time can significantly increase efficiency. Another way to modify a style at once is to modify the Class property, which is better for maintenance and reuse, although it may have a slight performance impact (checking cascading styles when changing classes)

11. There are three ways to get the DOM out of the document flow

    • Hide elements, apply changes, re-display
    • Use a document fragment to build a subtree outside the current DOM tree, and then copy back to the document
    • Copy the original element to a node that is out of the document, modify the copy, and replace the original element

12. Large-scale use of hover on IE 7-8 will slow down the response

13. With event delegation, you can reduce the number of binding events, which increases efficiency. Events that trigger a parent element by bubbling through child elements may be simpler and more elegant

14. Set the DOM node (animation element) that requires a lot of modification to absolute positioning, leaving it out of the document flow to reduce the impact

JavaScript performance optimization (i)

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.