2. 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
3. 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)
4. Why performance?
Better user experience (also, customers rarely complain about performance,
they just leave)
Google takes performance into account for PageRank
5. 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)
6. 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
7. 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’)
8. Always cache selectors when possible
BAD
var block = $(‘.block’);
var elements = $(‘.block’).find(‘.element’);
var title = $(‘.block’).data(‘title’);
GOOD
var block = $(‘.block’);
var elements = block.find(‘.element’);
var title = block.data(‘title’);
9. 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’);
10. 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)
11. Prefer group queries over loops
BAD
$(‘.element’).each(function() {
$(this).something().somethingElse();
});
GOOD
$(‘.element’).something().somethingElse();
12. Check if element exists before using it
BAD
$(‘.element’).slideDown();
GOOD
if ($(‘.element’).length) {
$(‘.element’).slideDown(); // this is a heavy call
}
13. 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