Advanced jQuery skills-performance optimization, jquery Performance Optimization

Source: Internet
Author: User
Tags jquery cdn

Advanced jQuery skills-performance optimization, jquery Performance Optimization
Introduce jQuery library through CDN (Content Delivery Network)

The simplest step to improve the performance of javascript on the website is to introduce the latest jQuery library. The new version usually improves the performance and fixes bugs. You can also use CDN to reduce the loading time of your website. Below are some CDN services:

<!-- Case 1 - jQuery CDN --><script src="http://code.jquery.com/jquery-1.10.2.min.js" ></script><!-- Case 2 - requesting jQuery from Googles CDN (notice the protocol) --><script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script><!-- Case 3 - requesting the latest minor 1.10.x version (only cached for an hour) --><script src="//ajax.googleapis.com/ajax/libs/jquery/1.10/jquery.min.js" ></script><!-- Case 4 - requesting the absolute latest jQuery version (use with caution) --><script src="http://code.jquery.com/jquery.min.js" ></script>

Some domestic CDN services:

Http://www.bootcdn.cn/jquery! -- Sina CDN --> <script src = "http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"> </script> <! -- Baidu CDN --> <script src = "http://libs.baidu.com/jquery/1.9.1/jquery.min.js"> </script> <! -- Bootstrap CDN --> http://www.bootcdn.cn/jquery/
Reduce DOM operations

Although javascript performance has been greatly improved, DOM operations are resource-consuming and need to be reduced. It is especially important to insert a large number of elements into a page. For example:

<div id="elem" ></div>
// Bad method // var elem =$ ('# elem'); // for (var I = 0; I <100; I ++) {// elem. append ('<li> element' + I + '</li> ');
//}

// Good method
Var elem = $ ('# elem '),
Arr = [];
For (var I = 0; I <100; I ++ ){
Arr. push ('<li> element' + I + '</li> ');
}
Elem. append (arr. join (''));

Caching all elements improves the performance of one insertion because only one re-painting of the page is triggered. The same applies to CSS style attributes.

Read more: What is the lag on the front-end page? It may be caused by DOM operations. You need to optimize the code.

Use native JS as appropriate

Creating a jQuery object will incur some overhead. Therefore, if you pay more attention to performance, try to use native javascript. In some ways, it may be easier to understand and write less code. For example:

// Print the li id $ ('# colors li') in the list '). each (function () {// set $ (this ). the attr ('id') method is replaced by directly accessing the console through the id attribute. log (this. id );})
Selector Optimization

If you need better performance but still need jQuery, you can try some optimization in the jQuery selector. The following is a test program. The console. time and console. timeEnd methods of the browser are used to record the execution time of different selectors.

HTML:

<div id="peanutButter" ><div id="jelly" class=".jellyTime" ></div></div>

JS:

// Test the program var iterations = 10000, I; // ---------------------------------------------- // Case 1: Very slow console. time ('fancy '); for (I = 0; I <iterations; I ++) {$ (' # peanutButter div: first ');} console. timeEnd ('fancy '); // ---------------------------------------------- // Case 2: relatively good, but still very slow console. time ('parent-child '); for (I = 0; I <iterations; I ++ ){
$ ('# PeanutButter div');} console. timeEnd ('parent-child '); // ---------------------------------------------- // Case 3: Some browsers will perform console operations faster. time ('parent-child by class'); for (I = 0; I <iterations; I ++) {// use the descendant class selector $ ('# peanutButter. jellytime');} console. timeEnd ('parent-child by class'); // ---------------------------------------------- // Case 4: Better console. time ('by class name'); 21for (I = 0; I <iterations; I ++) {// directly use the Class selector $ ('. jellytime');} console. timeEnd ('by class name'); // ---------------------------------------------- // Case 5: recommended method ID selector console. time ('by id'); for (I = 0; I <iterations; I ++) {$ ('# jel');} console. timeEnd ('by id ');

Execution result:

 

Cache jQuery objects

Every time a new jQuery object is built through a selector, the Sizzle engine of the core part of jQuery traverses the DOM and matches the real dom element through the corresponding selector. This method is inefficient. In modern browsers, you can use the document. querySelector method to pass in the corresponding Class parameter to match the corresponding element. However, IE8 or earlier versions do not support this method. One practice to improve performance is to cache jQuery objects through variables. For example:

<ul id="pancakes" >         <li>first</li>         <li>second</li>         <li>third</li>         <li>fourth</li>         <li>fifth</li></ul>

JS:

// Bad method: // $ ('# pancakes li '). eq (0 ). remove (); // $ ('# pancakes li '). eq (1 ). remove (); // $ ('# pancakes li '). eq (2 ). remove (); // ---------------------------------- // recommended method: var pancakes = $ ('# pancakes li'); pancakes. eq (0 ). remove (); pancakes. eq (1 ). remove (); pancakes. eq (2 ). remove (); // ------------------------------------ // or: // pancakes. eq (0 ). remove (). end ()//. eq (1 ). remove (). end ()//. eq (2 ). remove (). end ();
Define a reusable function

Example:

HTML:

<button id="menuButton" >Show Menu!</button><a href="#" id="menuLink" >Show Menu!</a>

JS:

// Bad: // This causes multiple callback function copies to occupy memory $ ('# menuButton, # menuLink '). click (function (){//...}); // ---------------------------------------------- // Betterfunction showMenu () {alert ('showing menu! '); // Doing something complex here} $ (' # menuButton '). click (showMenu); $ (' # menuLink '). click (showMenu );

If you define an inline callback function that contains multiple elements at the same time (as in the first example above ), each element in this set will save a copy of the callback function in the memory.

Use arrays to traverse jQuery object sets

You may not have noticed, but in terms of performance, there is a price for the elegant implementation of the jQuery each method. There is a way to traverse a jQuery object faster. It is implemented through arrays. The jQuery object set is a class array with the length and value attributes. You can test the performance through a program:

HTML:

<ul id="testList" >   <li>Item</li>   <li>Item</li>   <li>Item</li>   <li>Item</li>    <li>Item</li>   <li>Item</li>   <li>Item</li>   <li>Item</li>   <li>Item</li>   <!-- add 50 more --></ul>

JS:

Var arr = $ ('lil'), iterations = 100000; // ------------------------------ // Array Implementation: console. time ('native Loop '); for (var z = 0; z <iterations; z ++) {var length = arr. length; for (var I = 0; I <length; I ++) {arr [I] ;}} console. timeEnd ('native Loop '); // ------------------------------ // each implementation: console. time ('jquery reach'); for (z = 0; z <iterations; z ++) {arr. each (function (I, val) {this ;});} console. timeEnd ('jquery reach ');

Result:

We can see that the traversal through arrays is more efficient.

// ----------------------------------------------------------- Continuous update...

The above is a summary of some collected knowledge. If you have any suggestions or questions, please leave a message for discussion.

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.