JavaScript performance optimized DOM programming

Source: Internet
Author: User
Tags arithmetic bitwise

Recently studying high- performance JavaScript, here are some simple records. The sample code can be found here .

First, DOM

1) Dom and JavaScript

The Document Object Model (DOM) is a language-independent program Interface (API) for manipulating XML and HTML documents.

Browsers typically implement the DOM and JavaScript independently. For example, Chrome uses WebKit's WebCore library to render pages, using V8 as the JavaScript engine.

Access to the DOM is inherently slow, the DOM and JavaScript are likened to two islands, two peers to collect the bridge fee, ECMAScript access to the DOM more times, the more expensive the bridge, so the recommended practice is to minimize the number of crossings.

2) Performance test

is a performance test for two pieces of code, where you can view the online performance test .

1. Each cycle of the first paragraph is directly assigned with the DOM

2. The second paragraph is to cache the content into local variables, and then use the DOM assignment once.

The test results show the number of times the test code executes per second ( Ops/sec ), and the larger the value the better.

In addition to this result, statistical errors are also shown in the test process, as well as the relative best of how much slower (%), and statistical errors are very important indicators.

Second, selector API

Sometimes in order to get a list of required elements, you need to combine calls to getElementById and iterate through the returned nodes, but this dense process is inefficient.

Using CSS selectors is a convenient way to locate nodes, and Queryselectorall is the native method of Dom.

// Dom Combo API var elements = document.getElementById (' menu '). getElementsByTagName (' a '); // Replace with a simple CSS selector var elements = Document.queryselectorall (' #menu a ');

Three, redraw and rearrange

The general process of referring to page rendering inCSS animation and JavaScript animation is for JavaScript > Compute styles > Layout > Draw > Render layer merging.

Layout (reflow) and paint (redraw) are the most time-consuming two loops in the whole process, so we try to avoid these two links.

When DOM changes affect the geometric properties (width and height) of the element, it will occur 重排 (reflow);

When the reflow is complete, the browser redraws the affected section to the screen, which is 重绘 (repaint).

1) When the rearrangement occurs

1. Add or remove visible DOM elements

2. Element position Change

3. Element size change (including margin, padding, border width, width, advanced properties)

4. Changes in content, such as text changes or images are replaced by different sizes.

5. Page renderer initialization.

6. browser window size change.

2) Batch execution reflow

The code below looks like it will reflow 3 times, but in fact it will only rearrange 1 times, and most browsers optimize the re-typesetting process with queued modification and batch display.

// queuing and refreshing of render tree changes var ele = document.getElementById (' mydiv '= ' 1px' = ' 2px '= ' 5px ';

However, the following actions will force the queue to refresh and require that all planned changes be applied immediately:

Inch

Like the Offsetheight property needs to return the most recent layout information, so the browser has to perform "pending changes" in the render queue and trigger the reflow to return the correct values.

For information about dimensional coordinates, refer tojavascript dimensions, coordinates .

3) Minimize redraw and reflow

1. Csstext and Class

Csstext can set multiple CSS properties at once. Class can also be set at once, and clearer and easier to maintain, but with the precondition that it is not dependent on running logic and calculation.

// csstextele.style.cssText = ' border-left:1px; border-right:2px; padding:5px; ' ; // classele.classname = ' active ';

CSS-related JS operations are described in detail inJavaScript features (attribute), properties, and styles (style).

2. Batch Modify DOM

2.1 Hide Elements display:none , apply changes, re-display display:block .

2.2 Use the document fragment fragment , manipulate the node on the fragment, and then copy back to the document.

// document fragment (fragment) var fragment = document.createdocumentfragment (); var li = document.createelement (' li '= ' banana '; Fragment.appendchild (LI); document.getElementById (' fruit '). appendchild (fragment);

2.3 Copy the original element into a node that is out of the document (for example, Position:absolute), modify the copy, and then replace the original element.

Iv. Performance introduction of other chapters

1) Chapter One loading and execution

Place the <script> tag at the bottom of the page, that is, before the </body> close tag.

Multiple ways to download JavaScript without blocking:

1. Use the properties of the <script> tag defer . The page resolves to the <script> tab and starts downloading, but does not execute until the DOM is loaded ( onload before the event is triggered).

2. Dynamically create <script> elements to download and execute code. No matter when the download is initiated, the file's download and execution process does not block other processes on the page, but the returned code is usually executed immediately.

3. Use the Xhr object to download the JavaScript code and inject it into the page. The advantage is that it is not automatically executed after download, and is supported by all major browsers, but cannot be downloaded across domains.

2) Chapter II data Access

1. Each time a variable is encountered, it undergoes an identifier parsing process to determine where to fetch and store the data. In the scope of the execution environment, the deeper the identifier is located, the slower the read and write speed is. Therefore, reading and writing local variables is the fastest in a function, and reading and writing global variables is the slowest.

2. Because an object member may contain other members, for example window.location.href . Each time a dot operator is encountered, nested members cause the JavaScript engine to Search all object members . The deeper nesting of Object members, the slower the read speed. location.hrefIt's window.location.href faster than that.

3) The fifth chapter string and regular expression

str = str + "one"; // High performance str = "one" + str; // Poor performance

1. In addition to IE, the browser will simply copy the second string to the back of the first, if the variable str is large, there will be a performance loss (memory consumption) will be very high.

2. Regular optimization includes: reducing the number of branches, narrowing the range of branches, using a non-capturing array, capturing only the text of interest to reduce post-processing, using the appropriate quantifiers, simplifying the complex, and decomposing complicated regular;

4) Sixth Chapter Quick Response user interface

Using timers to let out time fragments, splitting large tasks, in the article "JavaScript Timer analysis " has a specific analysis.

5) Seventh Chapter Ajax

Mutipart XHRAllows clients to transfer multiple resources from the server to the client with only one HTTP request.

The resource file (CSS, HTML, JavaScript, Base64 encoded picture) is packaged into a string delimiter that is agreed by both parties and sent to the client.

The string is then processed in JavaScript code, and each resource is parsed according to the "mime-type" type and the incoming header information.

6) The Nineth chapter builds and deploys high-performance JavaScript applications

1. Merge JavaScript files to reduce the number of HTTP requests.

2. Compress JavaScript files.

3. Compress the JavaScript file (gzip encoded) on the server side.

4. Correctly set the HTTP response header to cache JavaScript files and avoid caching problems by adding timestamps to file names.

5. Use the CDN (Content Delivery Network) to provide JavaScript files.

In the eighth chapter, the programming practice content is more, separate make out as a section.

The eighth chapter of programming practice

1) Use Object/array Direct volume

code example:

var myObject = {   "Pwstrick",   + }; var myarr = ["Pwstrick", 29];

2) Avoid repetitive work

That is, lazy mode. Reduce the repetitive branch judgment of each code execution by masking the branch in the original object by redefining the object.

The lazy mode is divided into two types: the first file is executed immediately after the object method is redefined, and the second is redefined when the method object is used for the first time. Refer to the online demo code .

In the article "JavaScript design mode " There are more design patterns introduced.

3) Bit arithmetic

1. Use bit arithmetic instead of pure mathematical operation, for example, 2 modulo digit%2 can judge even and odd.

2. Bitmask technology, using each digit of a single digit to determine whether the option is true. The value of each option in the mask is a power of 2. For example:

var Option_a = 1, Option_b = 2, Option_c = 4, Option_d = 8, option_e = +; // Create a number with a bitwise OR operation to contain multiple settings options var options = Option_a | Option_c | Option_d; // you can then use the bitwise AND operation to determine whether a given option is available // whether option A is in the list if (Options & option_a) {  //...}

3. Use the bitwise Left SHIFT (<<) to multiply, use the bitwise right shift to divide (>>), for example, digit*2 replace digit<<2 .

4) Native method

No matter how your code is optimized, it's not as fast as the native method provided by the JavaScript engine.

1. Mathematical operations are provided in the built-in math object.

2. Use the native CSS selector to find the DOM node,queryselector or queryselectorall.

Resources:

High-performance JavaScript

Optimize the performance of Web applications with Jsperf

High-performance JavaScript DOM programming

Read "High performance JavaScript" notes (i)

High-performance JavaScript reflow and redraw

JavaScript performance optimized DOM programming

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.