SlideShare a Scribd company logo
jQuery Performance
   Tips & Tricks
   Addy Osmani, Jan 2011
About Me

Senior Web Developer (currently a PM)

jQuery Bug Triage, API Docs and Blogging
teams

Write for .NET magazine, my site and a few
other places.
I <3 jQuery
Why Performance?

Best practices are very important

Don’t follow them and browsers end up
having to do more work

More work = more memory usage = slower
apps..and you don’t want that.
Tip 1: Stay up to date!

ALWAYS use the latest version of jQuery core

Performance improvements and bug fixes are
usually made between each version

Older versions (eg. 1.4.2) won’t offer these
instant 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
                slow
if
(
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

//Selectors

1)
$(".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: Chaining
var
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 Delegation

Understand .bind(), .live() and .delegate() - do
you REALLY know the differences?

Delegates let you attach an event handler to a
common parent of your elements rather than a
discrete one to each of them

Also fires for NEW DOM nodes too

Use when binding same handler to multiple
elements
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
/*Let's
store
some
default
values
in
an
array*/
var
defaultSettings
=
{};
defaultSettings['carModel']


=
'Mercedes';
defaultSettings['carYear’]




=
2010;
defaultSettings['carMiles']


=
5000;
defaultSettings['carTint']



=
'Metallic
Blue';


/*Let's
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
don't)




*/









$.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 material


Twitter: @addyosmani / @addy_osmani


For my blog: http://addyosmani.com


GitHub: http://github.com/addyosmani

More Related Content

PPTX
Getting the Most Out of jQuery Widgets
velveeta_512
 
PPTX
FuncUnit
Brian Moschel
 
PPTX
Maintainable JavaScript 2012
Nicholas Zakas
 
PPT
jQuery 1.7 Events
dmethvin
 
PDF
jQuery Essentials
Bedis ElAchèche
 
KEY
jQuery Anti-Patterns for Performance & Compression
Paul Irish
 
PDF
jQuery Loves Developers - Oredev 2009
Remy Sharp
 
PDF
Rails 3: Dashing to the Finish
Yehuda Katz
 
Getting the Most Out of jQuery Widgets
velveeta_512
 
FuncUnit
Brian Moschel
 
Maintainable JavaScript 2012
Nicholas Zakas
 
jQuery 1.7 Events
dmethvin
 
jQuery Essentials
Bedis ElAchèche
 
jQuery Anti-Patterns for Performance & Compression
Paul Irish
 
jQuery Loves Developers - Oredev 2009
Remy Sharp
 
Rails 3: Dashing to the Finish
Yehuda Katz
 

What's hot (18)

PPT
jQuery
Mostafa Bayomi
 
PPTX
jQuery Presentation
Rod Johnson
 
PDF
Stack Overflow Austin - jQuery for Developers
Jonathan Sharp
 
PDF
jQuery in 15 minutes
Simon Willison
 
PDF
jQuery: Nuts, Bolts and Bling
Doug Neiner
 
PPTX
Introduction to jQuery
Gunjan Kumar
 
PDF
Drupal, meet Assetic
Kris Wallsmith
 
PPTX
jQuery Best Practice
chandrashekher786
 
PDF
jQuery UI and Plugins
Marc Grabanski
 
PDF
Plugin jQuery, Design Patterns
Robert Casanova
 
KEY
jQuery Plugin Creation
benalman
 
PPT
jQuery
Mohammed Arif
 
PDF
Write Less Do More
Remy Sharp
 
PDF
Javascript in Plone
Steve McMahon
 
KEY
SproutCore is Awesome - HTML5 Summer DevFest
tomdale
 
PDF
jQuery for beginners
Siva Arunachalam
 
KEY
jQuery('#knowledge').appendTo('#you');
mikehostetler
 
KEY
Bcblackpool jquery tips
Jack Franklin
 
jQuery Presentation
Rod Johnson
 
Stack Overflow Austin - jQuery for Developers
Jonathan Sharp
 
jQuery in 15 minutes
Simon Willison
 
jQuery: Nuts, Bolts and Bling
Doug Neiner
 
Introduction to jQuery
Gunjan Kumar
 
Drupal, meet Assetic
Kris Wallsmith
 
jQuery Best Practice
chandrashekher786
 
jQuery UI and Plugins
Marc Grabanski
 
Plugin jQuery, Design Patterns
Robert Casanova
 
jQuery Plugin Creation
benalman
 
Write Less Do More
Remy Sharp
 
Javascript in Plone
Steve McMahon
 
SproutCore is Awesome - HTML5 Summer DevFest
tomdale
 
jQuery for beginners
Siva Arunachalam
 
jQuery('#knowledge').appendTo('#you');
mikehostetler
 
Bcblackpool jquery tips
Jack Franklin
 
Ad

Similar to jQuery Performance Tips and Tricks (2011) (20)

KEY
jQuery: Tips, tricks and hints for better development and Performance
Jonas De Smet
 
PPTX
jQuery Performance Tips and Tricks
Valerii Iatsko
 
PPTX
jQuery performance best practices by Sameera Thilakasiri
Sameera Thilakasiri
 
PDF
jQuery Proven Performance Tips & Tricks
Addy Osmani
 
PPTX
SEF2013 - A jQuery Primer for SharePoint
Marc D Anderson
 
PDF
jQuery quick tips
Rochester Oliveira
 
PPTX
Java script performance tips
Shakti Shrestha
 
PPT
Kick start with j query
Md. Ziaul Haq
 
PPT
jQuery Performance Rules
nagarajhubli
 
PDF
jQuery - 10 Time-Savers You (Maybe) Don't Know
girish82
 
PPTX
SPTechCon DevDays - SharePoint & jQuery
Mark Rackley
 
PPT
Jquery Best Practices
brinsknaps
 
PPTX
J Query - Your First Steps
Bronson Quick
 
PPTX
SPSNH 2014 - The SharePoint & jQueryGuide
Mark Rackley
 
PPTX
SharePoint & jQuery Guide - SPSNashville 2014
Mark Rackley
 
PPSX
jQuery - Doing it right
girish82
 
PPTX
SPTechCon Boston 2015 - Utilizing jQuery in SharePoint
Mark Rackley
 
PPTX
SPTechCon - Share point and jquery essentials
Mark Rackley
 
PDF
Learning jquery-in-30-minutes-1195942580702664-3
luckysb16
 
KEY
jQuery Anti-Patterns for Performance
András Kovács
 
jQuery: Tips, tricks and hints for better development and Performance
Jonas De Smet
 
jQuery Performance Tips and Tricks
Valerii Iatsko
 
jQuery performance best practices by Sameera Thilakasiri
Sameera Thilakasiri
 
jQuery Proven Performance Tips & Tricks
Addy Osmani
 
SEF2013 - A jQuery Primer for SharePoint
Marc D Anderson
 
jQuery quick tips
Rochester Oliveira
 
Java script performance tips
Shakti Shrestha
 
Kick start with j query
Md. Ziaul Haq
 
jQuery Performance Rules
nagarajhubli
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
girish82
 
SPTechCon DevDays - SharePoint & jQuery
Mark Rackley
 
Jquery Best Practices
brinsknaps
 
J Query - Your First Steps
Bronson Quick
 
SPSNH 2014 - The SharePoint & jQueryGuide
Mark Rackley
 
SharePoint & jQuery Guide - SPSNashville 2014
Mark Rackley
 
jQuery - Doing it right
girish82
 
SPTechCon Boston 2015 - Utilizing jQuery in SharePoint
Mark Rackley
 
SPTechCon - Share point and jquery essentials
Mark Rackley
 
Learning jquery-in-30-minutes-1195942580702664-3
luckysb16
 
jQuery Anti-Patterns for Performance
András Kovács
 
Ad

More from Addy Osmani (6)

PDF
Open-source Mic Talks at AOL
Addy Osmani
 
PDF
Large-Scale JavaScript Development
Addy Osmani
 
PDF
Scalable JavaScript Design Patterns
Addy Osmani
 
PDF
Future-proofing Your JavaScript Apps (Compact edition)
Addy Osmani
 
PDF
Tools For jQuery Application Architecture (Extended Slides)
Addy Osmani
 
KEY
Evaluating jQuery Learning Material
Addy Osmani
 
Open-source Mic Talks at AOL
Addy Osmani
 
Large-Scale JavaScript Development
Addy Osmani
 
Scalable JavaScript Design Patterns
Addy Osmani
 
Future-proofing Your JavaScript Apps (Compact edition)
Addy Osmani
 
Tools For jQuery Application Architecture (Extended Slides)
Addy Osmani
 
Evaluating jQuery Learning Material
Addy Osmani
 

Recently uploaded (20)

PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Software Development Methodologies in 2025
KodekX
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 

jQuery Performance Tips and Tricks (2011)

Editor's Notes