jquery Performance Optimization 28 Tips you deserve to learn from _jquery

Source: Internet
Author: User
Tags extend wrapper
jquery Performance Tuning 28 tips have been looking for tips on optimizing jquery performance to make my bloated dynamic web apps lighter. After looking for a lot of articles, I decided to list some of the best and most common recommendations for optimizing performance. I also made a concise stylesheet of jquery performance optimizations that you can print out or set as a desktop background.
First, selector performance optimization recommendations
1. Always inherit from #id selector
This is a golden rule of the jquery selector. The quickest way for jquery to select an element is to select it with an ID.
Copy Code code as follows:

$ (' #content '). Hide ();

or inherit from ID selector to select multiple elements:
Copy Code code as follows:

$ (' #content p '). Hide ();

2. Use tag in front of class
The second fastest selector in jquery is the tag selector (such as $ (' head '), as it is getelementbytagname () directly from the native JavaScript method. So it's always best to use tag to decorate class (and don't forget the nearest ID)
Copy Code code as follows:

var receivenewsletter = $ (' #nslForm input.on ');

The class selector in jquery is the slowest because it iterates through all the DOM nodes in IE Explorer. Try to avoid using the class selector. Also do not use tag to decorate the ID. The following example iterates through all the DIV elements to find the node with the ID ' content ':
Copy Code code as follows:

var content = $ (' div#content '); Very slow, don't use

Using an ID to decorate the ID is also superfluous:
Copy Code code as follows:

var traffic_light = $ (' #content #traffic_light '); Very slow, don't use

3. Use a subquery
Cache the parent object for future use
Copy Code code as follows:

var Header = $ (' #header ');
var menu = Header.find ('. Menu ');
Or
var menu = $ ('. Menu ', header);

4. Optimize selector for sizzle "right to left" model
Since version 1.3, jquery has adopted the Sizzle library, which differs significantly from the previous version on the selector engine. It replaces the "right to left" model with the "left to right" model. Make sure the right selector is specific, and the selector on the left is wider:
Copy Code code as follows:

var linkcontacts = $ ('. Contact-links div.side-wrapper ');

and do not use
Copy Code code as follows:

var linkcontacts = $ (' a.contact-links. Side-wrapper ');

5. Use Find () instead of context lookup
. The find () function is really faster. But if a page has many DOM nodes, it may take more time to look back:
Copy Code code as follows:

var divs = $ ('. Testdiv ', ' #pageBody '); 2353 on Firebug 3.6
var divs = $ (' #pageBody '). Find ('. Testdiv '); 2324 on Firebug 3.6-the best time
var divs = $ (' #pageBody. Testdiv '); 2469 on Firebug 3.6

6. Use of powerful chain-type operation
Chained operations with jquery are more efficient than caching selectors:
Copy Code code as follows:

$ (' Li.menu-item '). Click (function () {alert (' Test click ');})
. CSS (' Display ', ' block ')
. css (' Color ', ' red ')
Fadeto (2, 0.7);

7. Write the selector that belongs to you
If you often use selectors in your code, extend jquery's $.expr[': ' Object, and write your own selector. In the following example, I created a abovethefold selector to select an element that is not visible:
Copy Code code as follows:

$.extend ($.expr[': '), {
Abovethefold:function (EL) {
Return $ (EL). Offset (). Top < $ (window). scrolltop () + $ (window). Height ();
}
});
var nonvisibleelements = $ (' div:abovethefold '); Select element

Ii. Optimizing DOM Operation recommendations
8. Caching jquery objects
Cache the elements you use frequently:
Copy Code code as follows:

var Header = $ (' #header ');
var divs = header.find (' div ');
var forms = Header.find (' form ');

9. Encapsulate all elements into one element when you want to do DOM inserts
The direct DOM operation is slow. Change the HTML structure as little as possible.
Copy Code code as follows:

var menu = ' <ul id= ' menu ' > ';
for (var i = 1; i < i++) {
Menu + + ' <li> ' + i + ' </li> ';
}
Menu + + ' </ul> ';
$ (' #header '). Prepend (menu);
Don't do this:
$ (' #header '). Prepend (' <ul id= ' menu ' ></ul> ');
for (var i = 1; i < i++) {
$ (' #menu '). Append (' <li> ' + i + ' </li> ');
}

10. Although jquery does not throw exceptions, developers should also examine objects
Although jquery does not throw a large number of exceptions to the user, the developer does not rely on this. jquery usually performs a lot of useless functions to determine whether an object exists. So before you make a series of references, you should check that the object exists.
11. Use a direct function instead of using a function equivalent to
To get better performance, you should use direct functions such as $.ajax () instead of using $.get (), $.getjson (), $.post (), because the next few will call $.ajax ().
12. Cache jquery results for later use
You often get a javasript app-you can use app to save objects you often choose for future use:
Copy Code code as follows:

App.hiddendivs = $ (' Div.hidden ');
And then call in your application:
App.hiddenDivs.find (' span ');

13. Use jquery's internal function data () to store the state
Don't forget to use the. Data () function to store information:
Copy Code code as follows:

$ (' #head '). Data (' name ', ' value ');
And then call in your application:
$ (' #head '). Data (' name ');

14. Using the jquery utility function
Don't forget the simple, practical jquery utility function. My favorite is $.isfunction (), $isArray () and $.each ().
15. Add "JS" class to HTML block
When jquery is loaded, first add a class called "JS" to HTML
Copy Code code as follows:

$ (' HTML '). addclass (' JS ');

You can add CSS styles only when the user has JavaScript enabled. For example:
Copy Code code as follows:

* * in CSS
. JS #myDiv {display:none;}

So when JavaScript is enabled, you can hide the entire HTML content and use jquery to implement what you want (for example, to put up some panels or expand when the user clicks on them). And when JavaScript is not enabled, the browser renders all the content, search engine crawler will also check everything. I will use this technique more in the future.
III. Recommendations for optimizing event performance
16. Defer to $ (window). Load
There are sometimes $ (window). Load () ratio $ (document). Ready () faster, because the latter does not wait for all DOM elements to be executed before the download is complete. You should test it before using it.
17. Use Event Delegation
When you have many nodes in a container and you want to bind an event to all nodes, delegation is a good fit for this scenario. With delegation, we only need to bind the event at the parent level, and then see which child node (the target node) triggers the event. When you have a table with a lot of data, you want to set up events for the TD node, which makes it very convenient. Get the table first, and then set the delegation event for all TD nodes:
Copy Code code as follows:

$ ("table"). Delegate ("TD", "hover", function () {
$ (this). Toggleclass ("hover");
});

18. Use shorthand for Ready events
If you want to compress the JS plugin, save every byte, you should avoid using $ (document). Onready ()
Copy Code code as follows:

Also do not use
$ (document). Ready (function () {
Code
});
You can be so short:
$ (function () {
Code
});

Four, test jquery
jquery Unit Test
The best way to test Javasript code is to test people. But you can use some automated tools such as Selenium,funcunit,quit,qmock to test your code (especially plug-ins). I would like to discuss this topic on another topic because there is so much to say.
20. Standardize your jquery code
Often standardize your code to see which query is slower and then replace it. You can use the Firebug console. You can also use jquery's shortcut functions to make testing easier:
Copy Code code as follows:

To record data shortcuts in the Firebug console
$.L ($ (' div '));

Copy Code code as follows:

Get UNIX Timestamp
$.time ();

Copy Code code as follows:

Time to execute code on Firebug record
$.lt ();
$ (' div ');
$.lt ();

Copy Code code as follows:

To put a code block in a for loop to test execution time
$.BM ("var divs = $ ('. Testdiv ', ' #pageBody ');"); 2353 on Firebug 3.6

Other common jquery performance optimization recommendations
21. Use the latest version of jquery
The latest version is often the best. After replacing the version, don't forget to test your code. Sometimes it's not completely backwards compatible.
22. Use of HMTL5
The new HTML5 Standard brings a more lightweight DOM structure. A lighter structure means that using jquery requires less traversal and better load performance. So please use HTML5 if possible.
23. Add a style label directly to the DOM element if you add more than 15 elements
The best way to add styles to a few elements is to use the Jquey CSS () function. However more than 15 more elements add styles, it is more efficient to add style labels directly to the DOM. This approach avoids the use of hard-coded (hard code) in your coding.
Copy Code code as follows:

$ (' <style type= ' text/css ' > Div.class {color:red;} </style> ')
. Appendto (' head ');

24. Avoid loading unwanted code
It's a good way to put JavaScript code in separate files, just load them when you need them. This way you don't load unnecessary code and selectors. It also makes it easier to manage code.
25. Compress into a main JS file, keep the download times to a minimum
When you have identified which files should be loaded, package them into a single file. Use some open source tools to automate your work, such as using minify (integrated with your back-end code) or using online tools like Jscompressor,yui compressor or Dean Edwards JS packer to compress your files. My favorite is jscompressor.
26. Use native Javasript when needed
Using jquery is a great thing to do, but don't forget it's also a framework for JavaScript. So you can use native JavaScript functions when the jquery code is necessary to get better performance.
27. Download the jquery framework from Google
When your application is officially online, download jquery from Google CDN because the user can get the code from the nearest place. This allows you to reduce server requests, and if the user browses to other sites, and it also uses Google CDN's jquery, the browser will immediately pull out the jquery code from the cache.
Copy Code code as follows:

Link a specific version of the compression code
<script type= "Text/javascript" src= "Https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" >< /script>

28. Slowly loading content can not only improve load speed, but also improve SEO optimization (Lazy load content for Speed and SEO benefits)
Use AJAX to load your site, which can save server-side loading time. You can start with a common sidebar widget.

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.