Home > Web Front-end > JS Tutorial > Use JQuery more efficiently. Here are 8 tips_jquery

Use JQuery more efficiently. Here are 8 tips_jquery

WBOY
Release: 2016-05-16 15:05:49
Original
1098 people have browsed it

1. DOM traversal is expensive, so cache variables.

Copy code The code is as follows:

//Not recommended
var h = $('#ele').height();
$('#ele').css('height', h-20);

Copy code The code is as follows:

//Recommend
var $ele = $('#ele');
var h = $ele.height();
$ele.css('height',h-20);

2. Optimize selectors.

Copy code The code is as follows:

//Not recommended
$('div#myid')

Copy code The code is as follows:

//Recommend
$('#myid')

3. Avoid implicit universal selectors.

Copy code The code is as follows:

//Not recommended
$('.someclass :radio')

Copy code The code is as follows:

//Recommend
$('.someclass input:radio')

4. Avoid universal selectors.

Copy code The code is as follows:

//Not recommended
$('.container > *')

Copy code The code is as follows:

//Recommend
$('.container').children()

5. Keep the code as simple as possible.

Copy code The code is as follows:

//Not recommended
if(arr.length > 0){}


Copy code The code is as follows:

//Recommended
if(arr.length){}

6. Merge functions as much as possible.

Copy code The code is as follows:

//Not recommended
$f.on("click", function(){
$(this).css('border','1px solid red');
$(this).css('color','blue');
});

Copy code The code is as follows:

//Recommend
$f.on("click", function(){
$(this).css({
         'border':'1px solid red',
'color': 'blue'
});
});

7. Use chain operations as much as possible.

Copy code The code is as follows:

//Not recommended
$ele.html();
$ele.on("click",function(){});
$ele.fadeIn('slow');

Copy code The code is as follows:

//Recommend
$ele.on("click",function(){

}).fadeIn('slow').animate({height:'12px'},500);

8. Perform a large number of operations on DOM elements, separate them first and then append them

Copy code The code is as follows:

//Not recommended
var $container = $('#somecontainer');
var $ele = $container.first();
.....A series of complex operations

Copy code The code is as follows:

//Recommend
var $container = $('#somecontainer');
var $ele = $container.first().detach();
.....A series of complex operations
$container.append($ele);
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