jQuery Performance Tips and Tricks (2011)
Upcoming SlideShare
Loading in...5
×
 

jQuery Performance Tips and Tricks (2011)

on

  • 8,613 views

Today we’re going to take a look at best practices, tips and tricks for improving the performance of your jQuery code. Performance optimization is a crucial aspect of building ‘snappy’ ...

Today we’re going to take a look at best practices, tips and tricks for improving the performance of your jQuery code. Performance optimization is a crucial aspect of building ‘snappy’ client-side applications and something which all developers using jQuery should bare in mind.

Statistics

Views

Total Views
8,613
Views on SlideShare
7,703
Embed Views
910

Actions

Likes
8
Downloads
139
Comments
0

11 Embeds 910

http://mambycamara.wordpress.com 841
http://labs.scaph.ru 35
http://192.168.1.101 8
http://magnit.local 8
http://translate.googleusercontent.com 6
http://localhost 3
http://prlog.ru 3
http://www.365dailyjournal.com 3
https://twimg0-a.akamaihd.net 1
http://us-w1.rockmelt.com 1
http://avielmed 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

jQuery Performance Tips and Tricks (2011) jQuery Performance Tips and Tricks (2011) Presentation Transcript

  • jQuery Performance Tips & Tricks Addy Osmani, Jan 2011
  • About MeSenior Web Developer (currently a PM)jQuery Bug Triage, API Docs and BloggingteamsWrite for .NET magazine, my site and a fewother places.
  • I <3 jQuery
  • Why Performance?Best practices are very importantDon’t follow them and browsers end uphaving to do more workMore work = more memory usage = slowerapps..and you don’t want that.
  • Tip 1: Stay up to date!ALWAYS use the latest version of jQuery corePerformance improvements and bug fixes areusually made between each versionOlder versions (eg. 1.4.2) won’t offer theseinstant benefits
  • Tip 2: Know Your Selectors All selectors are NOT created equally Fastest to slowest selectors are:◦ The
ID
Selectors
(“#AnElementWithID”)◦ Element
selectors
(“form”,
“input”,
etc.)◦ Class
selectors
(“.someClass”)◦ Pseudo
&
Attribute
selectors
(“:visible,
:hidden,
 [attribute=value]
etc.”) ID and element are fastest as backed by native DOM operations.
  • Pseudo-selectors: powerful but slowif
(
jQuery.expr
&&
jQuery.expr.filters
)
{
 jQuery.expr.filters.hidden
=
function(
elem
)
{
 
 var
width
=
elem.offsetWidth,
 
 
 height
=
elem.offsetHeight;
 
 return
(width
===
0
&&
height
===
0)
||
(!jQuery.support.reliableHiddenOffsets
&&
(elem.style.display
||
jQuery.css(
elem,
"display"
))
===
"none");
 };
 jQuery.expr.filters.visible
=
function(
elem
)
{
 
 return
!jQuery.expr.filters.hidden(
elem
);
 };} :hidden (above) is powerful but must be run against all the elements in your search space Pseudo/Attrib selectors have no browser-based call to take advantage of
  • A Look At Parents & Children//Selectors1)
$(".child",
$parent).show();
(Scope)2)
$parent.find(".child").show();
(using
find())3)
$parent.children(".child").show();
(immediate
children)4)
$("#parent
>
.child").show();
(via
CSS
selector)5)
$("#parent
.child").show();
(same
as
2)
  • Tip 3: Caching = Win.var
parents
=

$(‘.parents’);var
children
=
$(‘.parents’).find(‘.child’)
//bad Each $(‘.whatever’) will re-run your search of the DOM and return a new collection Bad! - use caching! (ie. parents. find(‘.child’)) You can then do whatever.show()/hide/stuff to your heart’s content.
  • Tip 4: Chainingvar
parents
=

$(‘.parents’).doSomething().doSomethingElse(); Almost all jQuery methods return a jQuery Object and support chaining After you’ve run a method on your selection, you can continue running more! Less code, easier to write and it runs faster!
  • No-chaining vs. chaining//Without
chaining$(‘#notification’).fadeIn(‘slow’);$(‘#notification’).addClass(‘.activeNotification’);$(‘#notification’).css(‘marginLeft’,
‘50px’);//With
chaining$(‘#notification’).fadeIn(‘slow’)

















.addClass(‘.activeNotification’)




















.css(‘marginLeft’,
‘50px’);
  • Tip 5: Event DelegationUnderstand .bind(), .live() and .delegate() - doyou REALLY know the differences?Delegates let you attach an event handler to acommon parent of your elements rather than adiscrete one to each of themAlso fires for NEW DOM nodes tooUse when binding same handler to multipleelements
  • Tip 6: The DOM isn’t a Database! jQuery lets you treat it like one, but that doesn’t make it so Every DOM insertion is costly Minimize by building HTML strings and using single a single append() as late as possible Use detach() if doing heavy interaction with a node then re-insert it when done
  • Quick Tip: Attaching Data A common way of attaching data is$(‘#item’).data(key,value); But this is significantly faster...$.data(‘#item’,
key,value);


















  • Tip 7: Avoid Loops. Nested DOM Selectors can perform better If not necessary, avoid loops. They’re slow in every programming language If possible, use the selector engine instead to address the elements that are needed There *are* places where loops can’t be substituted but try your best to optimize
  • Loops//Slow!$(#menu
a.submenu).each(
 
 function(index){
 
 
 $(this).doSomething()











.doSomethingElse();});//Better!$(#menu a.submenu).doSomething() .doSomethingElse();
  • Tip 8: Keep your code/*Non-Dry*/ DRY/*Lets
store
some
default
values
in
an
array*/var
defaultSettings
=
{};defaultSettings[carModel]


=
Mercedes;defaultSettings[carYear’]




=
2010;defaultSettings[carMiles]


=
5000;defaultSettings[carTint]



=
Metallic
Blue;
/*Lets
do
something
with
this
data
if
a
checkbox
is
clicked*/$(.someCheckbox).click(function(){










if
(this.checked){























$(#input_carModel).val(activeSettings.carModel);







$(#input_carYear).val(activeSettings.carYear);







$(#input_carMiles).val(activeSettings.carMiles);







$(#input_carTint).val(activeSettings.carTint);

}
else
{
























$(#input_carModel).val();












$(#input_carYear).val();








$(#input_carMiles).val();







$(#input_carTint).val();
}});
  • DRY-er code/*Dry*/$(.someCheckbox).click(function(){











var
checked
=
this.checked;



/*







What
are
we
repeating?







1.
input_
precedes
each
field
name







2.
accessing
the
same
array
for
settings







3.
repeating
value
resets









What
can
we
do?







1.
programmatically
generate
the
field
names







2.
access
array
by
key








3.
merge
this
call
using
terse
coding
(ie.
if
checked,












set
a
value,
otherwise
dont)



*/








$.each([carModel,
carYear,
carMiles,
carTint],
function(i,key){














$(#input_
+
v).val(checked
?
defaultSettings[key]
:
);






});});
  • When in doubt - Perf test! jsPerf.com - easy way to create tests comparing the perf of different JS snippets Uses Benchmark.js - a neat benchmarking utility that works cross-platform Easy to share your code or modify other tests
  • Thats it!Thanks to Matt Baker over at WealthFront for his very useful reference materialTwitter: @addyosmani / @addy_osmaniFor my blog: http://addyosmani.comGitHub: http://github.com/addyosmani