Cache the jquery object in the
for loop. Instead of accessing the length property of the array every time, we should cache the object into a variable first and then operate, as shown below:
var myLength = myArray.length;
for ( var i = 0; i < myLength; i ) {
// What to do
}
Use append
< outside the loop 🎜>There is a price for DOM manipulation. If you need to add a large number of elements to the DOM, you should do it in batches at a time instead of one at a time. // Don’t do this
$.each(reallyLongArray , function(count, item) {
var newLI = '
' item '';
$('#ballers').append(newLI);
}) ;
//Better practice
var frag = document.createDocumentFragment();
$.each(reallyLongArray, function(count, item) {
var newLI = '' item '';
frag.appendChild(newLI[0]);
});
$('#ballers')[0].appendChild(frag); Do not use each Using the $('#id') selector in () will traverse multiple times to find DOM elements, which is extremely inefficient. Use document.createDocumentFragment() to reduce the number of changes and refresh times to the DOM structure of the page
// Or like this
var myHtml = '';
$.each(myArray, function(i, item) {
html = '' item '' ;
});
$('#ballers').html(myHtml);
Keep it simple
// Not ideal
if ($ventfade.data('currently') != ' showing') {
$ventfade.stop();
}
if ($venthover.data('currently') != 'showing') {
$venthover.stop();
}
if ($spans.data('currently') != 'showing') {
$spans.stop();
}
// Better
var elems = [$ventfade, $venthover, $spans];
$.each(elems, function(k, v) {
if (v.data('currently') != 'showing') {
v.stop();
}
})
Use anonymous functions with caution
The constraints of anonymous functions are a pain everywhere. They are difficult to debug, maintain, test or reuse. Instead, we can use object encapsulation to organize and manage those handlers and callback functions through naming. // Don’t do this
$(document). ready(function() {...
$('#magic').click(function(e) {
$('#yayeffects').slideUp(function() {...
});
});
$('#happiness').load(url ' #unicorns', function() {...
})
});
// Better
var PI = {
onReady: function() {...
$('#magic').click(PI.candyMtn);
$(' #happiness').load(url ' #unicorns', PI.unicornCb);
},
candyMtn: function(e) {
$('#yayeffects').slideUp(PI.slideCb) ;
},
slideCb: function() {...
},
unicornCb: function() {...
}
}
$(document) .ready(PI.onReady);
Optimized selector
Node selection and DOM operation, matching an element based on a given ID always uses #id to find element // Very fast
$('# container div.robotarm');
// Super fast
$('#container').find('div.robotarm'); Using the $.fn.find method is faster because the first choice The selector does not need to be processed by the selector engine. The fastest selector in jquery is the ID selector. Because it comes directly from Javascript's getElementById() method, it is very fast because it is native to the browser. If you need to select multiple elements, this will inevitably involve DOM traversal and looping. In order to improve performance, it is recommended to inherit from the nearest ID.
Specify that the right part of the selector should be as specific as possible, while the left part need not be as specific.
// Not optimized
$('div. data .gonzalez');
// After optimization
$('.data td.gonzalez'); If possible, try to use tag.class on the right side of the selector, and only tag or Only .class.
Avoid being overly specific
$('.data table.attendees td.gonzalez');
// It would be better not to write the middle one
$('.data td.gonzalez'); The refreshing DOM structure also helps to improve selection With the performance of the selector, the selector engine can run fewer layers to find that element.
Avoid using undirected wildcard selectors
$('.buttons > *'); // Extremely slow
$('.buttons').children(); // Much faster
$('.gender :radio'); // Undirected search
$('.gender *:radio'); // Same as above
$('.gender input:radio'); // This is good Many
Use event delegation Event delegation allows you to bind an event handler to a container element (for example, an unordered list) without Each element in the container (for example, a list item) needs to be bound. jQuery provides $.fn.live and $.fn.delegate. If possible, you should use $.fn.delegate instead of $.fn.live as it eliminates the need for unnecessary selectors and reduces the context of its explicit case (the document context of $.fn.live) about 80% of the overhead. In addition to the performance benefits, event delegation also allows you to add new elements to the container without having to rebind the event because it already exists.
Bind multiple events at once through event delegation to reduce event redundancy
// Bad (if there are many elements in the list)
$('li.trigger').click(handlerFn);
// Better: event delegation with $.fn.live
$('li.trigger').live('click', handlerFn);
// Optimal: $.fn .delegate
$('#myList').delegate('li.trigger', 'click', handlerFn);
Remove element DOM The operation is slow and you should try to avoid operating it. jQuery introduced
$.fn.detach in version 1.4 to remove all matching elements from the DOM.
var $table = $('#myTable');
var $parent = table.parent();
$table.detach();
// ... add a large number of rows to the table
$parent.append(table);
.detach() is the same as .remove(), except that .detach() saves all jQuery data associated with the removed element. This method is useful when an element needs to be removed and later inserted into the DOM.
When modifying CSS for a large number of elements, you should use style sheets
If you are using $.fn.css to modify CSS for more than 20 elements, consider Add a style tag at once, which can increase the speed by 60%.
// More than 20 is obviously slow
$ ('a.swedberg').css('color', '#asd123');
$('