28 suggestions for jquery Performance Optimization

Source: Internet
Author: User
I. selector performance optimization suggestions

1. always inherit from the # ID Selector

This is a golden rule of jquery selector. The fastest way for jquery to select an element is to use ID.

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

You can also select multiple elements from the ID selector:

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

2. Use tags before the class

In jquery, the second-fastest selector is the tag selector (such as $ ('head'), because it is directly from the native JavaScript method getelementbytagname (). So it is best to always use tags to modify the class (and do not forget the nearest ID)

VaR incluenewsletter =ter ('# nslform input. on ');

In jquery, the class selector is the slowest, because in IE browser, it traverses all DOM nodes. Avoid using the class selector whenever possible. Do not use tags to modify the ID. The following example traverses all DIV elements to find the node with the ID of 'content:

VaR content = $ ('div # content'); // very slow, do not use

Using ID to modify the ID is also superfluous:

VaR traffic_light = $ ('# content # traffic_light'); // very slow, do not use

3. Use subquery

Cache the parent object for future use

VaR header = $ ('# head'); var menu = header. Find ('. Menu '); // or var menu = $ ('. Menu ', header );

Let's look at an example.

4. optimized the selector to apply the sizzle "from right to left" model.

Since version 1.3, jquery has adopted the sizzle library, which is very different from the previous version in the selector engine. It uses the "from left to right" model to replace the "from right to left" model. Make sure that the rightmost selector is specific, and the left selector has a wider range of options:

VaR linkcontacts = $ ('. Contact-links Div. Side-wrapper ');

Do not use

VaR linkcontacts = $ ('A. Contact-links. Side-wrapper ');

5. Use Find () instead of context search

The. Find () function is indeed faster. However, if a page has many DOM nodes and needs to be searched back and forth, it may take more time:

VaR divs = $ ('. testdiv ',' # pagebody '); // 2353 on firebug 3.6var divs =$ (' # pagebody '). find ('. testdiv '); // 2324 on firebug 3.6-the best timevar divs =$ (' # pagebody. testdiv '); // 2469 on firebug 3.6

6. Use powerful chain operations

The chain operation using jquery is more effective than the cache selector:

$ ('Li. menu-item '). click (function () {alert ('test click ');}). CSS ('display', 'block '). CSS ('color', 'red') fadeto (1, 0.7 );

7. compile your Selector

If youCodeTo use the selector, extend the $. expr [':'] object of jquery and compile your own selector. In the following example, I created an abovethefold selector to select invisible elements:

$. Extend ($. expr [':'], {abovethefold: function (EL) {return $ (EL ). offset (). top <$ (window ). scrolltop () + $ (window ). height () ;}}); var nonvisibleelements = $ ('div: abovethefold'); // select an element
Ii. Dom optimization suggestions

8. cache jquery objects

Cache frequently used elements:

VaR header = $ ('# head'); var divs = header. Find ('div'); var forms = header. Find ('form ');

9. When Dom insertion is required, all elements are encapsulated into one element.

Direct Dom operations are slow. Change the HTML structure as little as possible.

VaR menu = '<ul id = "menu">'; For (VAR I = 1; I <100; I ++) {menu + = '<li>' + I + '</LI>';} menu + = '</ul>'; $ ('# head '). prepend (menu); // do not do this: $ ('# head '). prepend ('<ul id = "menu"> </ul>'); For (VAR I = 1; I <100; I ++) {$ ('# menu '). append ('<li>' + I + '</LI> ');}

10. Although jquery does not throw an exception, developers should also check the object

Although jquery does not throw a large number of exceptions to users, developers should not rely on this. Jquery usually runs a lot of useless functions to determine whether an object exists. Therefore, before making a series of references to an object, check that the object does not exist.

11. Use direct functions instead of functions equivalent to them.

For better performance, you should use direct functions such as $. ajax () instead of $. get (), $. getjson (), $. post (), because the next few will call $. ajax ().

12. cache jquery results for future use

You will often get an javasript Application Object-you can use the app to save the objects you have selected for future use:

App. hiddendivs = $ ('div. Hidden '); // call app. hiddendivs. Find ('span') in your application ');

13. Use jquery's internal function data () to store the status

Do not forget to use the. Data () function to store information:

$ ('# Head '). data ('name', 'value'); // call $ ('# head') in your application '). data ('name ');

14. Use the jquery Utility Function

Don't forget the simple and practical jquery utility function. What I like most is $. isfunction (), $ isarray (), and $. Each ().

15. Add "JS" class to HTML Blocks

After jquery is loaded, add a class named "JS" to HTML.

$ ('Html '). addclass ('js ');

You can add CSS styles only when you enable Javascript. For example:

/* 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, collapse some panels or expand when users click them ). When Javascript is not enabled, the browser displays all the content, and the search engine crawler also hooks up all the content. I will use this technique more in the future.

Read more

Iii. Suggestions on optimizing event Performance

16. delay until $ (window). Load

Sometimes $ (window). Load () is faster than $ (document). Ready (), because the latter does not run until all DOM elements are downloaded. You should test it before using it.

17. Use event Delegation

When you have many nodes in a container and want to bind an event to all nodes, delegation is suitable for such application scenarios. When using delegation, we only need to bind events at the parent level, and then check which child node (target node) triggers the event. When you have a table with a lot of data, you want to set events for the TD node, which is very convenient. First obtain the table, and then set the delegation event for all TD nodes:

$ ("Table"). Delegate ("TD", "hover", function () {$ (this). toggleclass ("hover ");});

Read more

18. Use the abbreviation of ready event

If you want to compress the JS plug-in to save every byte, you should avoid using $ (document). onready ()

// Do not use $ (document ). ready (function () {// code}); // You Can Abbreviation: $ (function () {// code });
Iv. Test jquery

19. jquery unit test

The best way to test the javasript code is to test it by yourself. However, you can use automated tools such as selenium, funcunit, quit, and qmock to test your code (especially plug-ins ). I want to discuss this topic in another topic because there are too many things to talk about.

20. Standardize your jquery code

You often standardize your code to see which query is slow and then replace it. You can use the firebug console. You can also use jquery's shortcut functions to make testing easier:

// The data record shortcut on the firebug console $. L ($ ('div '));
// Obtain the Unix timestamp $. Time ();
// Record the code execution time in firebug $. LT (); $ ('div '); $. LT ();
// Place the code block in a for loop to test the execution time $. BM ("Var divs = $ ('. testdiv ',' # pagebody '); "); // 2353 on firebug 3.6
5. Other common jquery performance optimization suggestions

21. Use the latest version of jquery

The latest version is often the best. After changing the version, do not forget to test your code. Sometimes it is not completely backward compatible.

22. Use hmtl5

The new HTML5 standard provides a lightweight Dom structure. A lighter structure means that jquery requires less traversal and better loading performance. So use HTML5 if possible.

23. if you add a style to more than 15 elements, add the style label to the DOM element directly.

The best way to add styles to a few elements is to use the jquey CSS () function. However, it is more effective to directly add the style label to the DOM when more than 15 elements add styles. This method avoids hard code ).

$ ('<Style type = "text/CSS"> Div. Class {color: Red ;}</style>'). appendto ('head ');

24. Avoid loading unnecessary code

It is a good way to put JavaScript code in different files. Load them only when necessary. In this way, you will not load unnecessary code and selectors. It also facilitates code management.

25. compress the file into a main JS file to keep the download count to a minimum

When you have determined which files should be loaded, package them into a file. You can use some open-source tools to automatically compress your files, such as Minify (integrated with your back-end Code) or jscompressor, Yui compressor or Dean Edwards JS packer. My favorite is jscompressor.

26. Use the native javasript when necessary

Using jquery is a great thing, but don't forget that it is also a javascript framework. Therefore, you can use native JavaScript Functions when jquery code is necessary to achieve better performance.

27. Load the jquery framework from Google

When your application is officially launched, load jquery from Google CDN because you can get code from the nearest place. In this way, you can reduce server requests. If a user browses other websites and uses Google CDN's jquery, the browser immediately calls out the jquery code from the cache.

// Link the compression code of a specific version <SCRIPT type = "text/JavaScript" src = "https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"> </SCRIPT>

28. Slow loading of content not only improves loading speed, but also improves Seo Optimization(Lazy load content for speed and Seo benefits)

Use ajax to load your website, which can save loading time on the server. You can start with a common sidebar widget.

Thank you

In particular, thanks to Pau Irish, Addy Osmani, Jon Hobbs-Smith, and Dave artz for their useful information on jquery's performance optimization.

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.