jquery performance Optimization 38 recommends---the most compelling user experience!

Source: Internet
Author: User

One, need to be aware of is the definition of jquery when a variable is added Varkeyword
However, this is not jquery. Throughout the JavaScript development process, all you need to be aware of, be sure not to define it as the following example:
$loading = $ (' #loading '); This is a global definition, do not know where the unfortunate location of the same variable name, will be depressed to death

Second, use a var to define the variable
If you use more than one variable, define it in the following way, for example:

. The code is as follows:

Varpage = 0,
$loading = $ (' #loading '),
$body = $ (' body ');

Do not add a varkeyword to each variable unless you have severe obsessive-compulsive disorder.

Third, the definition of jquery variable is added to the $ symbol
When declaring or defining variables, remember to assume that you define a variable of jquery, adding a $ symbol to the variable before it. For example, the following:

. The code is as follows:

var$loading = $ (' #loading ');

This is defined here as the advantage. You can effectively prompt yourself or other users who read 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 is a process that consumes resources very much, and often very many people like to use jquery in this way:

. The code is as follows:


$ (' #loading '). html (' done ');
$ (' #loading '). FadeOut ();


No matter what the code is, you can execute the result normally, but notice that you actually create a new variable every time you define and call $ (' #loading '). If you need to reuse it, remember to define it in a variable so that you can cache the variable content effectively. For example, the following:

. The code is as follows:

var$loading = $ (' #loading ');
$loading. html (' done '); $loading. FadeOut ();

This will make the performance better.

V. Using chained operation
In the example above, we can write a little more concise:

. The code is as follows:


var $loading = $ (' #loading ');
$loading. html (' Done '). FadeOut ();


Vi. Streamlining the jquery code
Try to integrate some of the code together. Do not encode this:

. The code is 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:

. The code is as follows:

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


Vii. avoiding the use of global type selectors
Do not write as follows: $ (' .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 inference | | or && to speed up
Do not write as follows:

. The code is as follows:


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


This writing performance is better:

. The code is as follows:

$something = $something | | $ (' #something ');


Ten, try to use less code
Write it this way: if (string.length> 0) {...}
Why not write this: if (string.length) {...}

Xi. try to use the. On method
If you use a jquery class library with a newer version number, use. On. No matter what method is finally used. on to achieve.



12. jquery with the latest version number as far as possible
The latest version number of jquery has better performance, but the latest version number may not support IE6/7/8, so you need to choose for the actual situation.

13. Use native JavaScript as much as possible
It is assumed that the functionality provided by jquery can be implemented using native JavaScript as well. 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:

$ (' #contentp '). 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:

Varreceivenewsletter = $ (' #nslForm input.on ');


The class selector in jquery is the slowest, because it iterates through all of the DOM nodes in IE browser. Try to avoid using the class selector.

Also do not use tag to decorate the ID. The following sample iterates through the entire DIV element to find the node whose ID is ' content ':

. The code is as follows:

Varcontent = $ (' div#content '); Very slow. Do not use


It is also superfluous to decorate the ID with ID:

. The code is as follows:

Vartraffic_light = $ (' #content #traffic_light '); Very slow, do not use


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

. The code is as follows:

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


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

. The code is as follows:

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


and do not use

. The code is as follows:

Varlinkcontacts = $ (' 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 require a lot of other time to look back and forth:

. The code is as follows:

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


19. Write your own selector
Assuming 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 elements that are not visible:

. The code is 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:

. 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++) {
Menu + = ' <li> ' + i + ' </li> ';
}
Menu + = ' </ul> ';
$ (' #header '). 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 an exception. But developers should also check objects

Although jquery does not throw a large number of exceptions to the user, developers should not rely on this. jquery typically runs 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. Instead of using the equivalent function
For 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 Application Object--you can use the app. To save the objects you often choose for future use:

. 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 ');
It is then called in your app:
$ (' #head '). Data (' name ');


26. Using the jquery utility function
Don't forget the simple and useful 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 ');


Only when the user has JavaScript enabled, you have the ability to add CSS styles. Like what:

. The code is as follows:

/* in CSS */
. 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 the whole content. I will have many other uses of this technique in the future.



28, deferred to $ (window). Load
Sometimes use $ (window). Load () than $ (document). Ready () faster, because the latter does not wait until all of the DOM elements have been downloaded before they are run.

You should test it before using it.



29. Use Event Delegation
When you have a lot of nodes in a container. You want to bind an event to all of the nodes, delegation is ideal for this scenario. Use 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. This becomes very convenient. Get the table first and then set the delegation event for all TD nodes:

. The code is as follows:

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


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

. The code is as follows:

and 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 to test people.

But you can use some of your own proactive tools like selenium,funcunit,quit. Qmock to test your code (especially the plugin). I want to discuss this topic on another topic because there is so much to say.



32. Standardize your jquery code
Always 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 the test easier:

. The code is as follows:


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

Get UNIX Timestamp
$.time ();

Run code time in Firebug record
$.lt ();
$ (' div ');
$.lt ();

Put code blocks in a for loop test run time
$.BM ("var divs = $ ('. Testdiv ', ' #pageBody ');"); 2353 on Firebug3.6


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 if possible, use HTML5.

34. If you add styles to more than 15 elements, add a style tag to the DOM element directly
To add a style to a few elements. The best way to do this is to use the Jquey CSS () function. However, when more than 15 more elements are added to the style, it is more efficient to add a style tag directly to the DOM. 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 determined which files should be loaded. Then package them into a file. With some open source tools you can take the initiative to help you finish, such as using minify (and your backend code integration) or using Jscompressor,yui Compressor or Dean Edwards JS Packer and other online tools can compress files for you. What I like most is jscompressor.

37. Use native Javasript when required
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 loadcontent for Speed and SEO benefits)
Use AJAX to load your site. This saves server-side load time. You can start with a common sidebar widget.


The performance optimization of jquery is very important for high concurrency site development! Hope you can help! Installed in address forget. Excuse me!


Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

jquery performance Optimization 38 recommends---the most compelling user experience!

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.