JavaScript DOM programming Art (Detection and performance optimization)

Source: Internet
Author: User

First, object detection (whether the JS method is supported): only if the method is supported to invoke

if (!getelementbyid | | getElementsByTagName) {    returnfalse;}


Second, performance test filter

1. Minimize access to the DOM and minimize markup: Take the following code as an example

if (document.getElementsByTagName ("a"). Length > 0) {   var aliks = document.getElementsByTagName ("a");     for (var i = 0; i < aliks.length; i++) {     }}

This code is to find the <a> element in the DOM. If it is greater than 0, the number of <a> is obtained and iterated through. Here, two times, document.getElementsByTagName is used, and whenever you query an element in the DOM, the entire dom tree is searched, so this code performs a search more than once.

Optimized code:

var aliks = document.getElementsByTagName ("a"); if (Aliks.length > 0) {    for (var i = 0; i < aliks. length; i++) {     }} 

Iii. merging and placing scripts

<srcript src= "Js/a.js" ></script>

More use of external JS reference and the combination of multiple JS files into one, both can be pooled and reduce the number of requests sent when the page is loaded.

Iv. Compression Scripts

// get an array of objects var aliks = document.getElementsByTagName ("a"); if (Aliks.length > 0) {    // loops through for    (var i = 0; i < Aliks. Length i++) {     }}

After compression:

var aliks = document.getElementsByTagName ("a"); if (Aliks.length > 0) {for (var i = 0; i < aliks. length; i++) {}}

The streamlined script can reduce the size of the script although it does not understand it very well. In most cases we should have two versions of the script, a developed version with formatting and annotations that is easy to read, and a compact lite to be placed on the site.

JavaScript DOM programming art (Detection and performance optimization)

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.