Home > Web Front-end > JS Tutorial > How to write high-quality jQuery code (performance issues using jquery)_jquery

How to write high-quality jQuery code (performance issues using jquery)_jquery

WBOY
Release: 2016-05-16 16:42:56
Original
1306 people have browsed it

1. Correctly quote jQuery

1. Try to introduce jQuery before the end of the body, not in the head.
2. Use the CDN provided by a third party to introduce jQuery. At the same time, be careful to introduce local jQuery files when problems arise when using a third-party CDN. (This can be ignored for websites that have already used CDN. Now that user bandwidth has been upgraded, this can be ignored. Putting it on other people’s machines may not be stable)
3. If the script file is introduced before , there is no need to write document.ready, because the DOM has already been loaded when the js code is executed.

<body>
 <script src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script>
 <script>window.jQuery || document.write('<script src="jquery1.8.min.js">\x3C/script>')</script>
</body>
Copy after login

2. Optimize jQuery selector

Efficient and correct use of jQuery selectors is the basis for using jQuery proficiently. Mastering jQuery selectors requires a certain amount of time. We should pay attention to the use of selectors when we start learning jQuery.

<div id="nav" class="nav">
 <a class="home" href="http://www.jb51.net">脚本之家</a>
 <a class="articles" href="http://www.jb51.net/list/list_172_1.htm">jQuery教程</a>
</div>
Copy after login

If we select an element with class as home, we can use the following code:

$('.home'); //1
$('#nav a.home'); //2
$('#nav').find('a.home'); //3
Copy after login

1. Method 1 will make jQuery search for the a element with class home in the entire DOM, and the performance can be imagined.
2. Method 2 adds context to the element to be searched. Here it is changed to search for the sub-element with the id of nav. The search performance has been greatly improved.
3. Method 3 uses the find method, which is faster, so method 3 is the best.

Regarding the performance priority of jQuery selectors, ID selectors are faster than element selectors, and element selectors are faster than class selectors. Because ID selectors and element selectors are native JavaScript operations, but class selectors are not, you can take a look at the difference between find context and find() children.

3. Caching jQuery objects

Caching jQuery objects can reduce unnecessary DOM searches. Regarding this point, you can refer to caching jQuery objects to improve performance.

4. Correct use of event delegation
Event delegation can make events better executed. Binding events on dynamically added elements also requires delegation. In the new version of jQuery, it is recommended that you use on to bind one or more event processing to elements. function.

<table id="t">
 <tr>
  <td>我是单元格</td>
 </tr>
</table>

Copy after login

For example, if we want to bind a click event to the upper cell, a casual friend may write it as follows:

$('#t').find('td').on('click', function () {
 $(this).css({ 'color': 'red', 'background': 'yellow' });
});

Copy after login

This will bind events to each td. In the test of binding click events to 100 cells, the performance difference between the two is as much as 7 times. A good practice should be to write as follows:

$('#t').on('click', 'td', function () {
 $(this).css({ 'color': 'red', 'background': 'yellow' });
});

Copy after login

5. Streamline jQuery code
For example, in the above code, we have appropriately merged the jQuery code, and similarly the .attr() method, etc., but we have not written it in the following way:

$('#t').on('click', 'td', function () {
 $(this).css('color', 'red').css('background', 'yellow');
});

Copy after login

6. Reduce DOM operations
When you first start using jQuery, you may frequently operate the DOM, which is quite performance-consuming. If we want to dynamically output a table in the body, some friends will write like this:

var $t = $('body');
$t.append('<table>');
$t.append('<tr><td>1</td></tr>');
$t.append('</table>');

Copy after login

Good practices:

$('body').append('<table><tr><td>1</td></tr></table>');

Copy after login

In this way, after the table string is spliced ​​and then added to the body, the DOM operation only needs to be done once. A friend in the group used to have problems when outputting under IE because of this. Regarding string splicing, you can refer to the fastest method to create a string.

7. Do not use jQuery

Native functions are always the fastest. This is not difficult to understand. We should not forget native JS when writing code.

Let’s summarize these suggestions first. Each suggestion is not difficult to understand, but it will still take a lot of time to summarize comprehensively. For example, in the reduced code segment, if you need to get a new array from an array based on conditions, you can use the $.grep() method. If you have your own tips when using jQuery, please leave a comment. Share it with everyone!

The following are additions from other netizens:

Be careful to add the var keyword when defining jQuery variables
This is not only jQuery, but also needs to be paid attention to in all javascript development processes. Please do not define it as follows:

$loading = $('#loading'); //This is a global definition. If you accidentally reference the same variable name somewhere, you will be depressed to death

Please use a var to define variables
​If you use multiple variables, please define them as follows:

Copy code The code is as follows:

var page = 0,
$loading = $('#loading'),
$body = $('body');

Don’t add a var keyword to every variable unless you have severe obsessive-compulsive disorder
Define jQuery variables
When declaring or defining variables, please remember that if you are defining a jQuery variable, please add a $ symbol in front of the variable, as follows:

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

The advantage of defining it like this is that you can effectively remind yourself or other users who read your code that this is a jQuery variable.

Please remember to cache when operating DOM

In jQuery code development, we often need to operate DOM. DOM operation is a very resource-consuming process, and many people often like to use jQuery like this:

Copy code The code is as follows:

$('#loading').html('Complete');
$('#loading').fadeOut();

There is nothing wrong with the code, and you can run it normally and get results, but please note that every time you define and call $('#loading'), you actually create a new variable. If you need to reuse it, Remember to define it in a variable, so that the variable content can be effectively cached, as follows:

Copy code The code is as follows:

var $loading = $('#loading');
$loading.html('Finished');$loading.fadeOut();

The performance will be better this way.

Use chain operations

We can write the above example more concisely:

Copy code The code is as follows:

var $loading = $('#loading');
$loading.html('Finished').fadeOut();

Streamline jQuery code

Try to integrate some codes together, please do not code like this:

Copy code The code is as follows:

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

should be written like this:

Copy code The code is as follows:

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

Avoid using global type selectors

Please do not write in the following way: $('.something > *');
It’s better to write like this: $('.something').children();

Do not overlap multiple IDs

Please do not write as follows: $('#something #children');
This is enough: $('#children');

Use logical judgment || or && to speed up

Please do not write as follows:

Copy code The code is as follows:

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

Writing performance is better this way:

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


Use as little code as possible

Instead of writing like this: if(string.length > 0){..}

It’s better to write it like this: if(string.length){..}

Try to use the .on method
If you use a newer version of the jQuery class library, please use .on. Any other methods are ultimately implemented using .on.

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 according to the actual situation.

Try to use native Javascript
If the functions provided by jQuery can also be implemented using native Javascript, it is recommended to use native JavaScript to implement it.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template