jquery performance tips and tricks
TRANSCRIPT
jQuery PerformanceTips and Tricks
About Me
Front-end Developer at Booking.com
Previously worked as a Full-stack Developer at Art. Lebedev Studio
Technical writer, own blog https://www.codingbox.io/
Some other projects
I’m still using jQuery
Why:
It’s very quick and easy to start with jQuery
Allows to handle variety of browsers with ease
Where:
At work
For hobby-projects (e. g. I created oldams.nl using jQuery)
Yes, for some problems, jQuery might not be an optimal solution
Why performance?
Better user experience (also, customers rarely complain about performance, they just leave)
Google takes performance into account for PageRank
Basic tip. Stay up to date.
Always use the latest jQuery version, newer versions of jQuery contain performance improvements and security updates, thus benefit of upgrade is instant
Make sure you’re not harming customers with upgrade - use jQuery Migrate
Make sure site will work with injected older version of jQuery (don’t rely on globals $, jQuery)
Selectors
Selectors performance vary much
Fastest to slowest:ID selectors: $(‘#awesome-element’)Element selectors: $(‘form’)Class selectors: $(‘.awesome-element’)Pseudo & attribute selectors: $(‘[data-attr]’), $(‘:hidden’)
ID and element selectors are backed by Native DOM operations
jQuery uses right-to-left selectors engine
Same rule for querySelectorAll
Cases:$(‘div.page div.block .element’)$(‘div.page .element’)$(‘.page div.element’) best
$(‘#container’).find(‘.element’) way faster than $(‘#container .element’)
You can use context: $(‘.element’, ‘#container’)
Always cache selectors when possible
BADvar block = $(‘.block’);var elements = $(‘.block’).find(‘.element’);var title = $(‘.block’).data(‘title’);
GOODvar block = $(‘.block’);var elements = block.find(‘.element’);var title = block.data(‘title’);
Avoid DOM touches as much as possible
Example:
$(‘<style type=”text/css”>.awesome-class { color: red; }</style>’).appendTo(‘head’);
is taking ~ constant time in every case and might be faster than
$(‘.awesome-class’).css(‘color’, ‘red’);
Avoid DOM touches as much as possible
Prefer building HTML strings and use append() as late as possible
For heavy operations on existing DOM, use detach() and put it back later
Prefer .data() over .attr() to work with data associated with element (.data() allows you to avoid storing data in DOM)
Prefer group queries over loops
BAD$(‘.element’).each(function() { $(this).something().somethingElse();});
GOOD$(‘.element’).something().somethingElse();
Check if element exists before using it
BAD$(‘.element’).slideDown();
GOODif ($(‘.element’).length) { $(‘.element’).slideDown(); // this is a heavy call}
Read jQuery source when in doubt
https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.js
https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.js
https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.js
Thank you!Follow me:twitter.com/@viatskomedium.com/@viatskocodingbox.io