High-performance JavaScript reading notes (three. DOM programming 1)

Source: Internet
Author: User

Chapter three DOM Script DOM programming reading notes

Accessing and modifying DOM elements

Browsers often require DOM implementations and JavaScript to remain independent of each other.

<!--such as IE, a JavaScript implementation called JScript is located in the library file Jscript.dll, while the DOM implementation is located in another library Mshtml.dll (internal
Code trident). This separation technology allows other technologies and languages,
such as VBScript, benefit from the DOM functionality and rendering capabilities provided by Trident.
Safari uses WebKit's webcore to handle DOM and rendering with a separate JavaScriptCore engine.
Google Chrome also uses WebKit's WebCore library to render pages, but it implements its own JavaScript engine V8.
In Firefox, JavaScript implements Tracemonkey, separating it from its Gwcko rendering engine. -


accessing DOM elements

function Innerhtmlloop () {for (var count=0; count<15000; count++) {document.getElementById ("H"). innerhtml+= "A";}}

Each loop unit is accessed two times for the DOM element, read the innerHTML property again and again, and write once.

Use local variables to store updated content and write once at the end of the loop:

function Innerhtmlloop () {    var content= "";      for (var count=0; count<15000; count++) {        content+ = "a";    }     document.getElementById ("H"). innerhtml+= "Content";}

In all browsers, the new version runs much faster.

Conclusion: The more DOM you access, the slower your code will execute.
"Touch the DOM lightly" and try to keep it within the ECMAScript range.

Compare innerHTML and pure dom, such as createelement ()

Two ways to create a 1000-row table

1. Construct an HTML string, and then update the DOM's innerHTML property.

2. Document.createelement () document.createTextNode () through the standard Dom method.

The benefits of innerHTML are obvious on older browsers, and new browsers are less obvious.
Use the DOM method instead.

If you update a large piece of HTML page in a performance-critical operation, innerHTML executes faster in most browsers.
However, for most daily operations, the difference is not big, so it should be based on code readability, maintainability, team habits, code style to comprehensively determine the
which method to use.

Node cloning

Another way to update page content using the DOM method is to clone an existing DOM element instead of creating a new one.

Even with Element.clonenode () (element is an existing node) instead of document.createelement ();

In most browsers, cloning nodes is more efficient, but not much better. Regenerate the table in the previous example using the Clone node method.
The cell only creates a copy operation, so it's just a little bit faster.

HTML collection

is the class array object that holds the DOM node reference. The return value of the following function is a collection:

Document.getelementbyname ()
Document.getelementbyclassname ()
Document.getelementbytagname ()

Document.images all elements in the page
Document.links all the <a> elements
Document.forms All Forms
Document.forms[0].elements all fields of the first form in a page

These methods and properties return to the Htmlcollection object, which is a list of similar arrays . They are not arrays (because they do not have such things as push () and

Slice () method, but provides a length property)

The HTML collection actually queries the document, and when you update the information, repeat this query every time. For example, read the number of elements in the collection (i.e.
The length of the collection). This is the source of low efficiency.

Iterating over an array is significantly faster than an HTML collection of the same size and content, and you can copy the collection into an array of arr.

Each iteration of the process accesses the length property of the collection, causing the aggregate to be finer, resulting in noticeable performance loss in all browsers.


Optimization: caches the length property of the collection into a variable, and then uses the variable in the loop to determine the condition.

For any type of DOM access, if the same DOM property or method is accessed more than once, it is best to cache this DOM member with a local variable.
When traversing a collection, the first optimization is to store the collection reference in a local variable and cache the length property outside of the loop, and then, if in the loop body
Accesses the same collection element multiple times, it is cached with a local variable.


When using the DOM API, it is often necessary to select the most efficient API for a specific operation.


For example, to manipulate the surrounding elements, or to recursively iterate over all the child nodes, you can use the Childnode collection, or use nextsibling to get each element
Brother node.

Dom properties such as Childnode, FirstChild, nextsibling do not differentiate between element nodes and other types of nodes, such as annotation nodes and text nodes,
Usually only the element nodes need to be accessed, so in the loop, it seems that the node return type should be checked to filter out non-element nodes, these checks and
Filtering is an unnecessary DOM operation.


Returns only nodes of all types of ELEMENT nodes
Children ChildNodes
Childelementcount Childnodes.length
Firstelementchild FirstChild
Lastelementchild LastChild
Nextelementchild nextSibling
Previouselementsibling previoussibling

Above support FF3.5 Safari 4 chrome2 opera9.62
ie6,7,8 only supports children

Traversing children is faster than childnodes and has fewer collection items.

You can also use CSS selectors

var elements=document.queryselectorall ("#menu a");
Returns a nodelist-compliant class array object that does not return an HTML collection

The same way,
var Element=document.getelementbyid ("menu"). getElementsByTagName ("a");
This element will be an HTML collection, copy it into an array, and if you want to get the same return value type as Queryselectorall ()


Queryselectorall can also be used for federated queries
var errs=document.queryselectorall ("Div.warning,div.notice");
These two types of nodes can be obtained at once

Queryselector () returns the first node that meets the query criteria

High-performance JavaScript reading notes (three. DOM programming 1)

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.