38 Recommendations for jquery performance tuning _jquery

Source: Internet
Author: User
Tags wrapper

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

Copy Code code as follows:
var page = 0,
$loading = $ (' #loading '),
$body = $ (' body ');

Do not add a var keyword to each variable unless you have severe obsessive-compulsive disorder.
Three, define jquery variable is add $ symbol
When declaring or defining variables, keep in mind that if you are defining a jquery variable, add a $ symbol to the variable before, as follows:
Copy Code code as follows:
var $loading = $ (' #loading ');

The good thing about this is that you can effectively prompt yourself or other users who read your code, which is a jquery variable.
Iv. DOM Operations be sure to remember caching (cache)
In jquery code development, we often need to manipulate dom,dom operations is a very resource consuming process, and often many people like to use jquery:
Copy Code code as follows:

$ (' #loading '). html (' finished ');
$ (' #loading '). fadeout ();

The code doesn't have any problems, you can also run the results normally, but notice that each time you define and call $ (' #loading '), you actually create a new variable, and if you need to reuse it, remember to define it in a variable so that you can effectively cache the variable contents as follows:
Copy Code code as follows:
var $loading = $ (' #loading ');
$loading. HTML (' finished '); $loading. fadeout ();

This will improve performance.
v. Use chain operation
The above example, we can write a little more concise:
Copy Code code as follows:

var $loading = $ (' #loading ');
$loading. HTML (' finished '). fadeout ();

Vi. streamlining jquery code
Try to integrate some of the code together, do not encode this:
Copy Code code as follows:

!! Villain
$button. Click (function () {
$target. css (' width ', ' 50% ');
$target. CSS (' border ', ' 1px solid #202020 ');
$target. CSS (' color ', ' #fff ');
});

It should be written like this:
Copy Code code as follows:
$button. Click (function () {
$target. css ({' width ': ' 50% ', ' border ': ' 1px solid #202020 ', ' Color ': ' #fff '});
});

Vii. Avoid using a global type selector
Do not write in the following way: $ ('. something > * ');
This is better to write: $ ('. something '). Children ();
Eight, do not stack multiple IDs
Do not write as follows: $ (' #something #children ');
That's enough: $ (' #children ');
Multi-use logic judgment | | or && to speed up
Please do not write as follows:
Copy Code code as follows:

if (! $something) {
$something = $ (' #something ');
}

This writing performance is better:
Copy Code code as follows:
$something = $something | | $ (' #something ');

10, try to use less code
Write this: if (String.Length > 0) {.}
Write like this: if (string.length) {...}
11, as far as possible use. On Method
Use. On if you use the new version of the JQuery class library, and any other method is ultimately used. 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, try to use native JavaScript
If using native JavaScript can also implement the functionality that jquery provides, it is recommended to use native JavaScript for implementation.
14, always from the #id selector to inherit
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 ();

15. 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

16. Use subqueries
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);

17. 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 ');

18, use Find (), and do not use 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

19, write your own selector
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

20. 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 ');

Encapsulate all elements into one element when you want to do DOM inserts

21, the direct DOM operation is very 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> ');

}
22, 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.
23. 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 ().
24. 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 ');

25, using the internal function of jquery 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 ');

26. Use jquery utility function
Don't forget the simple, practical jquery utility function. My favorite is $.isfunction (), $isArray () and $.each ().
27. 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.
28, deferred 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.
29. 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");
});

30, the use of ready events shorthand
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
});

31. 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.
three 12, 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 '));

Get UNIX Timestamp
$.time ();

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

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


33. Use 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.
34. Add a style label to a DOM element if you add styles to 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 ');

35, to avoid loading redundant 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.
36, compressed into a main JS file, the number of downloads to keep to the 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.
37. 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.
38, slow 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.