I have been searching for tips on jQuery performance optimization to make my bloated dynamic web application lighter. After finding many articles, I decided to list some of the best and most commonly used performance optimization suggestions. I have also made a concise jQuery performance optimization style sheet, you can print it out... SyntaxHighlighter. all ();
I have been searching for tips on jQuery performance optimization to make my bloated dynamic web application lighter. After finding many articles, I decided to list some of the best and most commonly used performance optimization suggestions. I also made a concise jQuery performance-optimized style sheet, which can be printed out or set as a desktop background.
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.
1 $ ('# content'). hide ();
You can also select multiple elements from the ID selector:
1 $ ('# 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)
1 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:
1 var content = $ ('div # content'); // very slow, do not use
Using ID to modify the ID is also superfluous:
1 var traffic_light = $ ('# content # traffic_light'); // very slow, do not use
3. Use subquery
Cache the parent object for future use
1
2
3
4 var header = $ ('# header ');
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:
1 var linkContacts = $ ('. contact-links div. side-wrapper ');
Do not use
1 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:
1
2
3 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 powerful chain operations
The chain operation using jQuery is more effective than the cache selector:
1
2
3
4 $ ('Li. menu-item'). click (function () {alert ('test click ');})
. Css ('display', 'block ')
. Css ('color', 'red ')
FadeTo (2, 0.7 );
7. compile your Selector
If you often use selector in code, extend the $. expr [':'] object of jQuery and write your own selector. In the following example, I created an abovethefold selector to select invisible elements:
1
2
3
4
5
6 $. 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:
1
2
3 var header = $ ('# header ');
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.
1
2
3
4
5
6
7
8
9
10
11 var menu ='
';
For (var I = 1; I <100; I ++ ){
Menu + ='
- '+ I +'
';
}
Menu + ='
';
$ ('# Head'). prepend (menu );
// Do not do this:
$ ('# Head'). prepend ('
');
For (var I = 1; I <100; I ++ ){
$ ('# Menu'). append ('
'+ I +'');
}
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:
1
2
3 App. hiddenDivs =$ ('div. Den den ');
// Call the following in your application:
App. hiddenDivs. find ('span ');
13. Use jQuery's internal function data () to store the status
Do not forget to use the. data () function to store information:
1
2
3 $ ('# head'). data ('name', 'value ');
// Call the following in your application:
$ ('# Head'). 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.
1 $ ('html '). addClass ('js ');
You can add CSS styles only when you enable JavaScript. For example:
1
2/* 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:
1
2
3 $ ("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 ()
1
2
3
4
5
6
7
8 // do not use
$ (Document). ready (function (){
// Code
});
// You Can abbreviated it as follows:
$ (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:
1
2 // quick way to record data on the Firebug Console
$. L ($ ('div '));
1
2 // obtain the UNIX Timestamp
$. Time ();
1
2
3
4 // record the code execution time in Firebug
$. Lt ();
$ ('Div ');
$. Lt ();
1
2 // 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 ).
1
2 $ ('')
. 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.
1
2 // link the compression code of a specific version