jquery Performance Optimization Advanced techniques _jquery

Source: Internet
Author: User
Tags jquery library jquery cdn

Sometimes when we write jquery, it's easy to write code that ignores the pressure on the client during the execution of the program. This has been followed by problems such as slow or even inability to run on some low-end browsers or low-end computers.

So it is necessary to optimize our own jquery code to achieve faster and smoother results.

jquery performance Optimization advanced techniques, the following mainly from seven aspects of jquery performance optimization to do introduction:

1. Introduction of jquery library via CDN (Content Delivery Network)

2. Reduce DOM operations

3. Proper use of native JS

4. Selector optimization

5. Caching jquery objects

6. Define a function that can be reused

7. Iterate through the collection of jquery objects by array

Here is a detailed description of each method:

Introduction of jquery library via CDN (Content Delivery Network)

One of the easiest steps to improve the performance of JavaScript in a Web site is to introduce the latest version of the jquery library, where new releases typically improve performance and fix bugs. or through the introduction of CDN is also a good choice, through the introduction of CDN can reduce the load time of the site.

Here 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 Googles CDN (Notice the Protocol)--> <script
"src=" Eapis.com/ajax/libs/jquery/1.10.2/jquery.min.js "></script>
<!--case 3-requesting the latest minor 1.10.x version (only cached for a 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 of the 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

While JavaScript performance has been greatly improved, DOM operations are still resource-intensive and need to be reduced to DOM operations. This is especially important when you insert a large number of elements into a page.

For example:

<div id= "Elem" ></div>

//Bad way
//var elem = $ (' #elem ');
for (var i = 0; i < i++) {
//elem.append (' <li>element ' +i+ ' </li> ');
//Good way
var elem = $ (' #elem '),
arr = [];
for (var i = 0; i < i++) {
arr. push (' <li>element ' +i+ ' </li> ');
}
Elem. Append (arr. Join ("));

Caching all of the elements increases in performance at one time, because only the page is redrawn once. The same is true for CSS style attributes.

Read MORE: Front page cotton? It could be the DOM operation, you need to optimize the code

Proper use of native JS

Creating a JQuery object can incur some overhead. So, if you pay more attention to performance, use native JavaScript whenever possible. In some ways it may be easier to understand and write less code. For example:

Prints the ID of Li in the list
$ (' #colors Li '). each (function () {
//the $ (this). attr (' id ') method is substituted for access to
console. Log directly through the ID property ( This. ID);
}

Selector optimization

If you need better performance, but still need to use jquery, you can make some attempts at jquery selector optimization. The following is a test program that records different selector execution times through the browser's console Console.time and Console.timeend methods.

Html:

<div id= "Peanutbutter" > <div id= "Jelly" class= "Jellytime" ></div> </div> JS://test program Var Iterat
ions = 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 be faster Console.time (' Parent-child by class '); for (i = 0; i < iterations i++) {//through descendant class selector $ (' #peanutButter. Jellytime ');} console.timeend (' Parent-child b
Y class ');
--------------------------------------------//case 4: Better Way Console.time (' by class name ');
for (i = 0; i < iterations i++) {//Directly through class selector $ ('. Jellytime ');} console.timeend (' By class name '); //--------------------------------------------//case 5: Recommended Way ID selector console.time (' by id '); for (i = 0; i < iterations. i++) {$ (' #jelly ');} console.timeend (' by id ');

Execution results:

Caching jquery Objects

Each time a new jquery object is built through the selector, the sizzle engine of the core of jquery traverses the DOM and then matches the real DOM element with the corresponding selector. This approach is relatively inefficient, and in modern browsers the Document.queryselector method can be used to match the corresponding elements by passing in the corresponding class parameters, although IE8 the following version does not support this method. A high performance practice 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 way:
//$ (' #pancakes li '). EQ (0). Remove ();
$ (' #pancakes li '). EQ (1). Remove ();
$ (' #pancakes li '). EQ (2). Remove ();
------------------------------------
//Recommended way:
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 function that can be reused

Directly on Example:

HTML:
<button id= "Menubutton" >show menu!</button> <a href= "
#" id= "Menulink" >show Menu! </a>

Js:

Bad: 
//This will cause a copy of multiple callback functions to occupy memory
$ (' #menuButton, #menuLink '). Click (function () {
//...
});
----------------------------------------------
//better
function ShowMenu () {
alert (' showing menu! ');
Doing something complex here
}
$ (' #menuButton '). Click (showmenu);
$ (' #menuLink '). Click (ShowMenu);

If you define an inline (inline) callback function and the jquery object that contains multiple elements (as the first example above), each element in the collection holds a copy of the callback function in memory.

Iterate through the collection of jquery objects by array

You may not have noticed, but in terms of performance there is a price for this elegant implementation of the jquery each method. There is a way to traverse a jquery object more quickly. is implemented through arrays, the JQuery object collection is an array of classes with length and value attributes. You can test performance by using 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 more-->
</ul>

Js:

var arr = $ (' li '),
  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 each ');
for (z = 0; z < iterations; z++) {
  Arr.each (function (i, Val) {this
    ;
  })
Console.timeend (' JQuery each ');

Results:

You can see that traversal through array implementation is more efficient.


-------------------------------------------------------Continuous Update ...

The above is a collection of knowledge of the summary, if you have any suggestions or questions, welcome to the message 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.