SlideShare uma empresa Scribd logo
1 de 23
jQuery performance tips
  Web should be snappy, not sloppy




               by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   1
Most popular sites using jQuery on




                                                                  Picture from internet


            by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast              2
Fast: ID & Element Selectors
$(‘#Element, form, input’)

ID and element selectors are the fastest
This is because they’re backed by native DOM
operations (eg. getElementById()).




                    by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   3
Slower: Class Selectors
$(‘.element’)

getElementsByClassName() not supported in IE5-8
Supported in FF3+, Safari 4+, Chrome 4+, Opera 10.10+
so faster in these.




                    by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   4
Slowest: Pseudo & Attribute Selectors
$(‘:visible, :hidden’);
$(‘[attribute=value]’);

This is due to no native calls available that we can take
advantage of.
querySelector() and querySelectorAll() help with this in
modern browsers.



                     by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   5
Understand parents and children
1) $(‘.child", $parent).show(); //context
2) $parent.find(‘.child’).show(); //find()
3) $parent.children(".child’).show(); //immediate
children
4) $(‘#parent > .child’).show(); //child combinator
selector
5) $(‘#parent .child’).show(); //class selector
6) $('.child', $('#parent')).show(); //created context


                      by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   6
Context
$(‘.child’, $parent).show();



Here the scope must be parsed and
translated to $.parent.find(‘child’).show();
causing it to be slower.

~5-10% slower than the fastest option

                      by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   7
find()
$parent.find(‘.child’).show();



This is the fastest of the entire set. I’ll explain why
shortly.




                       by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   8
Immediate children
$parent.children(‘.child’).show();

Internally uses $.sibling and JavaScript’s nextSibling() to
find nodes following other nodes in the same tree.

~50% slower than the fastest option




                      by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   9
CSS child combinatory selector

$(‘#parent > .child’).show();

Uses a child combinatory selector, however Sizzle works
from right to left.
Bad as it will match .child before checking it’s a direct
child of the parent.
~70% slower than the fastest option



                     by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   10
CSS class selector
$(‘#parent .child’).show();

Uses a class selector and is constrained by the same
rules as 4).
Internally also has to translate to using .find()
~77% slower than the fastest option




                     by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   11
Created context
$(‘.child’, $(‘#parent’)).show();

Equivalent internally to
$(‘#parent’).find(‘.child’), however note that parent is a
jQuery object.
~23% slower than the fastest option




                      by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   12
The fastest option is..
$parent.find(‘.child’).show();

The parent selector is already cached here, so it doesn’t
need to be refetched from the DOM.
Without caching this is ~ 16% slower.
Directly uses native
getElementById, getElementsByName, getElementsByT
agName to search inside the passed context under the
hood.

                     by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   13
Why not use the DOM
element itself? This is faster:

$('a').bind(‘click’, function(){
     console.log('You clicked: ' + this.id);
});




                    by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   14
Caching is the best practice
var   parents = $(‘.parents’), //caching
      children = $(‘.parents’).find(‘.child’), //bad
      kids = parents.find(‘.child’); //good




Caching just means we’re storing the result of a
selection for later re-use.




                     by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   15
So remember..
Each $(‘.elem’) will re-run your search of the DOM and
return a new collection
You can then do anything with the cached collection.
Caching will decrease repeat selections.




                     by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   16
Chaining
var parents = $(‘.parents’).doSomething().doSomethingElse();



Almost all jQuery methods return a jQuery object and
support chaining.
This means after executing a method on a
selection, you can continue executing more.
Less code and it’s easier to write!




                        by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   17
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’);




                     by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   18
Better .append() usage
Minimise use by building HTML strings in memory and
using a single .append() instead.
Multiple appends can be up to 90% slower when not
appending to cached selectors and up to 20% slower
with them.




                   by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   19
Use .detach()
Works great when you’re doing heavy interaction with
a node
Allows you to re-insert the node to the DOM once
you’re ready
Up to 60% faster than working with undetached nodes.




                   by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   20
Better .data() usage
We usually attach data like this..
But this is actually much faster..
$(‘#elem’).data( key , value );
$.data(‘#elem’, key , value);

as there’s overhead creating a jQuery object and doing
data-parsing in the first.



                      by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   21
Thank you




by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   22
Author
Sameera Thilakasiri is a front-end developer based in Colombo. Specialist in
UI, UX, SEO, IA, IxD, RWD. He is blogging technical areas and lifestyle
photographer while is leisure. He can be reached by
http://www.sameerast.com or @sameerast




                            by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast   23

Mais conteúdo relacionado

Destaque (6)

Berlin m pstories
Berlin m pstoriesBerlin m pstories
Berlin m pstories
 
Vincent celii
Vincent celiiVincent celii
Vincent celii
 
Measuring and Improving Decision Quality
Measuring and Improving Decision QualityMeasuring and Improving Decision Quality
Measuring and Improving Decision Quality
 
Para que sirven las frutas
Para que sirven las frutasPara que sirven las frutas
Para que sirven las frutas
 
KPR
KPRKPR
KPR
 
NGO Day 2013
NGO Day 2013NGO Day 2013
NGO Day 2013
 

Semelhante a jQuery performance best practices by Sameera Thilakasiri

jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)Addy Osmani
 
Don't Worry jQuery is very Easy:Learning Tips For jQuery
Don't Worry jQuery is very Easy:Learning Tips For jQueryDon't Worry jQuery is very Easy:Learning Tips For jQuery
Don't Worry jQuery is very Easy:Learning Tips For jQueryshabab shihan
 
SharePoint & jQuery Guide - SPSNashville 2014
SharePoint & jQuery Guide - SPSNashville 2014SharePoint & jQuery Guide - SPSNashville 2014
SharePoint & jQuery Guide - SPSNashville 2014Mark Rackley
 
jQuery Performance Tips and Tricks
jQuery Performance Tips and TricksjQuery Performance Tips and Tricks
jQuery Performance Tips and TricksValerii Iatsko
 
Search Form for Rails
Search Form for RailsSearch Form for Rails
Search Form for Railssinsoku listy
 
So long, jQuery, and thanks for all the fish!
So long, jQuery, and thanks for all the fish!So long, jQuery, and thanks for all the fish!
So long, jQuery, and thanks for all the fish!Matt Turnure
 
Efficient use of jQuery selector
Efficient use of jQuery selectorEfficient use of jQuery selector
Efficient use of jQuery selectorchandrashekher786
 
SPTechCon DevDays - SharePoint & jQuery
SPTechCon DevDays - SharePoint & jQuerySPTechCon DevDays - SharePoint & jQuery
SPTechCon DevDays - SharePoint & jQueryMark Rackley
 
The Web Components interoperability challenge - Horacio Gonzalez - Codemotion...
The Web Components interoperability challenge - Horacio Gonzalez - Codemotion...The Web Components interoperability challenge - Horacio Gonzalez - Codemotion...
The Web Components interoperability challenge - Horacio Gonzalez - Codemotion...Codemotion
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsMark Rackley
 
Bcblackpool jquery tips
Bcblackpool jquery tipsBcblackpool jquery tips
Bcblackpool jquery tipsJack Franklin
 
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analystsMeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analystsSimo Ahava
 
2009 Barcamp Nashville Web Security 101
2009 Barcamp Nashville   Web Security 1012009 Barcamp Nashville   Web Security 101
2009 Barcamp Nashville Web Security 101brian_dailey
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Craig Francis
 
jQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksjQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksAddy Osmani
 
Even faster web sites
Even faster web sitesEven faster web sites
Even faster web sitesFelipe Lavín
 
SPTechCon Boston 2015 - Utilizing jQuery in SharePoint
SPTechCon Boston 2015 - Utilizing jQuery in SharePointSPTechCon Boston 2015 - Utilizing jQuery in SharePoint
SPTechCon Boston 2015 - Utilizing jQuery in SharePointMark Rackley
 

Semelhante a jQuery performance best practices by Sameera Thilakasiri (20)

jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)
 
Don't Worry jQuery is very Easy:Learning Tips For jQuery
Don't Worry jQuery is very Easy:Learning Tips For jQueryDon't Worry jQuery is very Easy:Learning Tips For jQuery
Don't Worry jQuery is very Easy:Learning Tips For jQuery
 
SharePoint & jQuery Guide - SPSNashville 2014
SharePoint & jQuery Guide - SPSNashville 2014SharePoint & jQuery Guide - SPSNashville 2014
SharePoint & jQuery Guide - SPSNashville 2014
 
jQuery Performance Tips and Tricks
jQuery Performance Tips and TricksjQuery Performance Tips and Tricks
jQuery Performance Tips and Tricks
 
Search Form for Rails
Search Form for RailsSearch Form for Rails
Search Form for Rails
 
So long, jQuery, and thanks for all the fish!
So long, jQuery, and thanks for all the fish!So long, jQuery, and thanks for all the fish!
So long, jQuery, and thanks for all the fish!
 
Efficient use of jQuery selector
Efficient use of jQuery selectorEfficient use of jQuery selector
Efficient use of jQuery selector
 
SPTechCon DevDays - SharePoint & jQuery
SPTechCon DevDays - SharePoint & jQuerySPTechCon DevDays - SharePoint & jQuery
SPTechCon DevDays - SharePoint & jQuery
 
The Web Components interoperability challenge - Horacio Gonzalez - Codemotion...
The Web Components interoperability challenge - Horacio Gonzalez - Codemotion...The Web Components interoperability challenge - Horacio Gonzalez - Codemotion...
The Web Components interoperability challenge - Horacio Gonzalez - Codemotion...
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentials
 
68837.ppt
68837.ppt68837.ppt
68837.ppt
 
Bcblackpool jquery tips
Bcblackpool jquery tipsBcblackpool jquery tips
Bcblackpool jquery tips
 
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analystsMeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
 
2009 Barcamp Nashville Web Security 101
2009 Barcamp Nashville   Web Security 1012009 Barcamp Nashville   Web Security 101
2009 Barcamp Nashville Web Security 101
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()
 
jQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksjQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & Tricks
 
Even faster web sites
Even faster web sitesEven faster web sites
Even faster web sites
 
SPTechCon Boston 2015 - Utilizing jQuery in SharePoint
SPTechCon Boston 2015 - Utilizing jQuery in SharePointSPTechCon Boston 2015 - Utilizing jQuery in SharePoint
SPTechCon Boston 2015 - Utilizing jQuery in SharePoint
 
Gems Of Selenium
Gems Of SeleniumGems Of Selenium
Gems Of Selenium
 
javascript
javascriptjavascript
javascript
 

Último

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 

Último (20)

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 

jQuery performance best practices by Sameera Thilakasiri

  • 1. jQuery performance tips Web should be snappy, not sloppy by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 1
  • 2. Most popular sites using jQuery on Picture from internet by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 2
  • 3. Fast: ID & Element Selectors $(‘#Element, form, input’) ID and element selectors are the fastest This is because they’re backed by native DOM operations (eg. getElementById()). by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 3
  • 4. Slower: Class Selectors $(‘.element’) getElementsByClassName() not supported in IE5-8 Supported in FF3+, Safari 4+, Chrome 4+, Opera 10.10+ so faster in these. by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 4
  • 5. Slowest: Pseudo & Attribute Selectors $(‘:visible, :hidden’); $(‘[attribute=value]’); This is due to no native calls available that we can take advantage of. querySelector() and querySelectorAll() help with this in modern browsers. by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 5
  • 6. Understand parents and children 1) $(‘.child", $parent).show(); //context 2) $parent.find(‘.child’).show(); //find() 3) $parent.children(".child’).show(); //immediate children 4) $(‘#parent > .child’).show(); //child combinator selector 5) $(‘#parent .child’).show(); //class selector 6) $('.child', $('#parent')).show(); //created context by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 6
  • 7. Context $(‘.child’, $parent).show(); Here the scope must be parsed and translated to $.parent.find(‘child’).show(); causing it to be slower. ~5-10% slower than the fastest option by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 7
  • 8. find() $parent.find(‘.child’).show(); This is the fastest of the entire set. I’ll explain why shortly. by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 8
  • 9. Immediate children $parent.children(‘.child’).show(); Internally uses $.sibling and JavaScript’s nextSibling() to find nodes following other nodes in the same tree. ~50% slower than the fastest option by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 9
  • 10. CSS child combinatory selector $(‘#parent > .child’).show(); Uses a child combinatory selector, however Sizzle works from right to left. Bad as it will match .child before checking it’s a direct child of the parent. ~70% slower than the fastest option by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 10
  • 11. CSS class selector $(‘#parent .child’).show(); Uses a class selector and is constrained by the same rules as 4). Internally also has to translate to using .find() ~77% slower than the fastest option by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 11
  • 12. Created context $(‘.child’, $(‘#parent’)).show(); Equivalent internally to $(‘#parent’).find(‘.child’), however note that parent is a jQuery object. ~23% slower than the fastest option by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 12
  • 13. The fastest option is.. $parent.find(‘.child’).show(); The parent selector is already cached here, so it doesn’t need to be refetched from the DOM. Without caching this is ~ 16% slower. Directly uses native getElementById, getElementsByName, getElementsByT agName to search inside the passed context under the hood. by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 13
  • 14. Why not use the DOM element itself? This is faster: $('a').bind(‘click’, function(){ console.log('You clicked: ' + this.id); }); by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 14
  • 15. Caching is the best practice var parents = $(‘.parents’), //caching children = $(‘.parents’).find(‘.child’), //bad kids = parents.find(‘.child’); //good Caching just means we’re storing the result of a selection for later re-use. by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 15
  • 16. So remember.. Each $(‘.elem’) will re-run your search of the DOM and return a new collection You can then do anything with the cached collection. Caching will decrease repeat selections. by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 16
  • 17. Chaining var parents = $(‘.parents’).doSomething().doSomethingElse(); Almost all jQuery methods return a jQuery object and support chaining. This means after executing a method on a selection, you can continue executing more. Less code and it’s easier to write! by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 17
  • 18. 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’); by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 18
  • 19. Better .append() usage Minimise use by building HTML strings in memory and using a single .append() instead. Multiple appends can be up to 90% slower when not appending to cached selectors and up to 20% slower with them. by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 19
  • 20. Use .detach() Works great when you’re doing heavy interaction with a node Allows you to re-insert the node to the DOM once you’re ready Up to 60% faster than working with undetached nodes. by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 20
  • 21. Better .data() usage We usually attach data like this.. But this is actually much faster.. $(‘#elem’).data( key , value ); $.data(‘#elem’, key , value); as there’s overhead creating a jQuery object and doing data-parsing in the first. by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 21
  • 22. Thank you by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 22
  • 23. Author Sameera Thilakasiri is a front-end developer based in Colombo. Specialist in UI, UX, SEO, IA, IxD, RWD. He is blogging technical areas and lifestyle photographer while is leisure. He can be reached by http://www.sameerast.com or @sameerast by Sameera Thilakasiri | www.sameerast.com | Twitter @ sameerast 23