Tips and Tricks to improve JQuery efficiency
3145 단어 jquery
Tips and Tricks to improve JQuery efficiency
* Always use the latest version of jQuery core where possible.
* Use faster selector
- id selector, tag selector > class selector > pseudoclass selector, attribute selector
* Faster way to get child ele from a parent ele.
- $parent.find('.child')
* Don't use jQuery unless it's absolutely necessary
- javascript's original methods are faster.
* Do cache
- var parents = $('.parents'); // caching
{
// bad way
children = $('.parents').find('.child');
others = $('.parents').find('.others');
}
{
// better way, use cache
children = parents.find('.child');
others = parents.find('.others')
}
* Chaining
- e.g. var parents = $('.parents').doSomething().doSomethingElse();
- in this way, jQuery will cache the result of each step automatically,
so it's faster than non-chaining way.
* Use event delegation
- javascript allow events to bubble up the DOM tree to a parent element.
as "<table><tr></tr>...<tr></tr></table>", it's better to bind a single
event handler to <table> element than each <tr> element.
2 ways for delegation:
1) // .delegate() method
$("td").bind("click",function(){
$(this).toggleClass("click");
});
2) // .live() method
$("table").each(function(){
$("td",this).live("click", function(){
$(this).toggleClass("click");
});
});
Difference:
.delegate() fire when event bubble to the specific parent element.
.live() fire when event bubble to the root element.
so .delegate() is a little faster than .live()
* You'd better not to modify the DOM tree
- each DOM insertion is costly. so be careful to use append(),
insertBefore(), insertAfter()
if you want to insert several element items, you can put them together
and use a single append() method
- when you're doing heavy interaction with a node, you should use .detach() method first.
- if you're to attach data to a node, please use $.data(elem,key,value)
//bad
var ele = $('#elem');
ele.data(key, value);
//good, 10 times faster than above one
var ele = $('#elem');
$.data(ele, key, value);
* Understand loops
- unless absolutely necessary, avoid loops.
- javascript's for, while statement is faster than jQuery.each() method
* Avoid constructing new jQuery object unless necessary
- // slower
var $text = $('#text');
var $ts = $text.text();
// faster
var $text = $('#text');
var $ts = $.text($text);
// http://addyosmani.com/jqprovenperformance/
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
jQuery 전후 예이 기사에서는 jquery after() 및 before() 메소드의 예를 볼 것입니다. before() 메서드는 선택한 요소 앞에 지정된 콘텐츠를 삽입합니다. after() 메서드는 선택한 요소 뒤에 지정된 콘텐츠...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.