Performance optimization for jquery 38 small details

Source: Internet
Author: User

First, note when defining jquery variables, add the var keyword
This is not just jquery, all the JavaScript development process, you need to be aware of, please do not define as follows:
$loading = $ (' #loading '); This is a global definition, do not know where the unfortunate location of the same variable name, you will be depressed to death
Second, use a var to define the variable
If you use multiple variables, define them as follows:

The code is as follows:
1 var page = 0,2 $loading = $ (' #loading '),3 $body = $ (' body ');
View Code

Do not add a var keyword to every variable unless you have severe obsessive-compulsive disorder.
Third, the definition of jquery variable is to add the $ symbol
When declaring or defining variables, keep in mind that if you define a variable of jquery, add a $ symbol to the variable before it, as follows:

The code is as follows:
var $loading = $ (' #loading ');
View Code

The benefit of defining this is that you can effectively prompt yourself or other users who are reading your code, which is a jquery variable.
Iv. DOM Operations Be sure to remember the cache
In the development of jquery code, we often need to manipulate dom,dom operations as a process that consumes resources very often, and many people like to use jquery in this way:

The code is as follows:

$ (' #loading '). html (' finished '); $ (' #loading '). FadeOut ();
View Code

The code does not have any problems, you can also run the results, but note that each time you define and call $ (' #loading '), the actual creation of a new variable, if you need to reuse, remember to define a variable, so that you can effectively cache the contents of the variable, as follows:

The code is as follows:
var $loading = $ (' #loading '); $loading. html (' finished '); $loading. FadeOut ();
View Code

This will make the performance better.
V. Using chained operation
The above example, we can write a little more concise:

The code is as follows:
var $loading = $ (' #loading '); $loading. html (' finished '). FadeOut ();
View Code

Vi. Streamlining the jquery code
Try to integrate some code together, so do not encode:

The code is as follows:
// ! Villain $button. Click (function() {$target. css (' width ', ' 50% '); $target. css (' border ', ' 1px solid #202020 '); $target. css (' color ', ' #fff ');});
View Code

It should be written like this:

The code is as follows:
$button. Click (function() {$target. css ({' width ': ' 50% ', ' border ': ' 1px solid #202020 ', ' Color ': ' #fff '});
View Code

Vii. avoiding the use of global type selectors
Do not write in the following ways: $ ('. something > * ');
This is better written: $ ('. something '). Children ();
Eight, do not overlay multiple IDs
Do not write as follows: $ (' #something #children ');
This is enough: $ (' #children ');
Nine, multi-use logical judgment | | or && to speed up
Do not write as follows:

The code is as follows:
if (!  = $ (' #something ');}

This writing performance is better:

The code is as follows:
$something = $something | | $ (' #something ');

Ten, try to use less code
Write it like this: if (String.Length > 0) {...}
Why not write this: if (string.length) {...}
Xi. try to use the. On method
If you are using a newer version of the JQuery class library, use. On, and any other method is finally implemented using. On.
12. Try to use the latest version of jquery
The latest version of jquery has better performance, but the latest version may not support IE6/7/8, so you need to choose for yourself.
13. Use native JavaScript as much as possible
If the functionality provided by jquery can be implemented using native JavaScript, it is recommended to use native JavaScript.
14. Always inherit from #id selector
This is a golden rule of the jquery selector. jquery the quickest way to select an element is to select it with an ID.

The code is as follows:
$ (' #content '). Hide ();

or inherit from the ID selector to select multiple elements:

The code is as follows:
$ (' #content p '). Hide ();

XV, use tag in front of class
The second fastest selector in jquery is the tag selector (such as $ (' head ')) because it is getelementbytagname () directly from the native JavaScript method. So it's best to always use tag to modify class (and don't forget the nearest ID)

The code is 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 browser. Try to avoid using the class selector. Also do not use tag to decorate the ID. The following example iterates through all DIV elements to find the node whose ID is ' content ':

The code is as follows:
var // very slow, do not use

It is also superfluous to decorate the ID with ID:

The code is as follows:
var // very slow, do not use

16. Using sub-query
Cache the parent object for future use

The code is as follows:
var header = $ (' #header '); var menu = Header.find ('. Menu '); // or var menu = $ ('. Menu ', header);

17. Optimized selector for sizzle "right-to-left" model
Since version 1.3, jquery has adopted the Sizzle library, which differs greatly from the previous version's representation on the selector engine. It replaces the "right-to-left" model with a "left-to-right" model. Make sure the right-most selector is specific, and the selector on the left is wider:

The code is as follows:
var linkcontacts = $ ('. Contact-links div.side-wrapper ');

and do not use

The code is as follows:
var linkcontacts = $ (' a.contact-links. Side-wrapper ');


18. Use Find () instead of context lookup
The. Find () function is indeed faster. However, if a page has many DOM nodes, it may take more time to look back and forth:

The code is as follows:
var // 2353 on Firebug 3.6 var // 2324 on Firebug 3.6-the best time var // 2469 on Firebug 3.6

19. Write your own selector
If you often use selectors in your code, expand jquery's $.expr[': ' Object and write your own selector. In the following example, I created a abovethefold selector to select an invisible element:

The code is as follows:
$.extend ($.expr[': 'function(EL) {return $ (EL). Offset (). Top < $ (window). ScrollTop () + $ (window). Height ();}); var // Select Element

20. Caching jquery Objects
Cache the elements you often use:

The code is as follows:
var header = $ (' #header '); var divs = header.find (' div '); var forms = Header.find (' form ');

Encapsulates all elements into one element when you want to make a DOM insert

21, the direct DOM operation is very slow. Change the HTML structure as little as possible.

The code is as follows:
var menu = ' <ul id= ' menu > ';  for (var i = 1; i <; i+++ = ' <li> ' + i + ' </li> '+ = ' </ul> '; $ (' #hea Der '). prepend (menu); // Never do this:$ (' #header '). Prepend (' <ul id= ' menu ></ul> ');  for (var i = 1; i < i++) {$ (' #menu '). Append (' <li> ' + i + ' </li> ');}

22. Although jquery does not throw exceptions, developers should also check objects

Although jquery does not throw a large number of exceptions to the user, developers do not rely on this. jquery usually executes a whole bunch of useless functions before determining whether an object exists. So before you make a series of references to a, you should check that the object does not exist.
23. Use direct functions rather than functions that are equivalent to them
For better performance, you should use direct functions such as $.ajax () instead of $.get (), $.getjson (), $.post (), since several of the following will call $.ajax ().
24. Cache jquery results for later use
You often get a Javasript Application Object--you can use the app. To save the objects you choose frequently for future usage:

The code is as follows:
App.hiddendivs = $ (' Div.hidden '); // It is then called in your app: App.hiddenDivs.find (' span ');

25, using the internal function of jquery data () to store the state
Don't forget to use the. Data () function to store information:

The code is as follows:

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

26. Using the jquery utility function
Don't forget the simple and practical utility function of jquery. My favorite is $.isfunction (), $isArray () and $.each ().
27. Add "JS" Class for HTML block
When jquery is loaded, first add a class called "JS" to the HTML

The code is as follows:
$ (' HTML '). addclass (' JS ');

You can add CSS styles only when the user has JavaScript enabled. For example:

The code is as follows:
/**/. JS #myDiv {display:none;}

So when JavaScript is enabled, you can hide the entire HTML content and use jquery to do what you want to do (for example, to pick up some panels or expand when the user clicks them). And when JavaScript is not enabled, the browser renders all the content, and the search engine crawler will also tick all the content. I will use this technique more in the future.
28, deferred to $ (window). Load
Sometimes it takes $ (window). Load () than $ (document). Ready () is faster because the latter does not wait for all DOM elements to be downloaded before they are finished. You should test it before you use it.
29. Use Event Delegation
When you have many nodes in a container and you want to bind an event to all of the nodes, delegation is a good fit for such an application scenario. With delegation, we only need to bind the event at the parent level and then see which child node (the target node) triggered the event. When you have a table with a lot of data, you want to set events on the TD node, which makes it very convenient. Get the table first and then set the delegation event for all TD nodes:

The code is as follows:
function () {$ (this). Toggleclass ("hover");});

30. Shorthand for using the Ready event
If you want to compress the JS plugin and save every byte, you should avoid using $ (document). Onready ()

The code is as follows:
// also do not use $ (document). Ready (function  () {//  code }); // You can do this:$ (function  () {//  Code });

31. jquery Unit Test
The best way to test Javasript code is for people to test. But you can use some automated tools like Selenium,funcunit,quit,qmock to test your code (especially plugins). I want to discuss this topic on another topic because there is so much to say.
three 12. Standardize your jquery code
Always 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 code is as follows:
 //  Shortcut to record data in Firebug console  $.l ($ (' Div '  //  get unix timestamp  $.time ();  //  Execute code time in Firebug record  $.lt (); $ ( ' div '  //  Put the code block in a for loop to test execution time  $.bm ("var divs = $ ('. Testdiv ', ' #pageBody ');"); //  

33. Using HMTL5
The new HTML5 Standard brings a lighter DOM structure. A lighter structure means that using jquery requires less traversal and better load performance. So please use HTML5 if possible.
34. Add style labels to DOM elements when adding styles to more than 15 elements
The best way to add styles to a small number of elements is to use the Jquey CSS () function. However, adding a style to the DOM is more effective when adding more than 15 more elements. This approach avoids hard coding in code.

The code is as follows:
$ (' <style type= ' text/css ' > Div.class {color:red;} </style> '). AppendTo (' head ');

35. Avoid loading redundant code
Putting JavaScript code in different files is a good way to load them only when you need them. This way you do not load unnecessary code and selectors. It is also easy to manage code.
36, compressed into a main JS file, the download times to keep to a minimum
When you have identified which files should be loaded, package them as a file. With some open source tools you can do it automatically, such as using minify (and your backend code integration) or using online tools such as Jscompressor,yui Compressor or Dean Edwards JS packer to compress files for you. What I like most is jscompressor.
37. Use native Javasript when needed
Using jquery is a great thing, but don't forget it's also a framework for JavaScript. So you can also use native JavaScript functions when the jquery code is necessary to get better performance.
38, slow loading content can not only improve loading speed, but also improve SEO optimization (Lazy load content for Speed and SEO benefits)
Use AJAX to load your site, which saves server loading time. You can start with a common sidebar widget.

Performance optimization for jquery 38 small details

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.