SlideShare uma empresa Scribd logo
1 de 25
Performance optimization
Front End meeting
30th June 2011

Filip Mares
Agenda
•Blocking and long running scripts
•Slow CSS Selectors on IE
•Too many XHR calls, requesting unnecessary data
•Expensive DOM Manipulations
•Leverage Event Delegation (event bubbling)
•Defer script loading and execution
Blocking and long running scripts
•Improve the Time to First Impression and Time to onLoad
•Script execution slows down the overall page load time
•Script blocks that execute longer than 20ms have potential for
improvement
Blocking and long running scripts
•First Impression
great if < 1s, acceptable if < 2.5s and slow if > 2.5s
•onLoad Event (DOM ready)
great if < 2s, acceptable if < 4s and slow if > 4s
•Fully Loaded (window load)
great if < 2s, acceptable if < 5s and slow if > 5s

(based on dynaTrace research)
Slow CSS Selectors on IE
Eliminate jQuery class Selectors
•Use Unique ID instead when possible
•Specify a Tag name if you have to use the Class Name
•Specify a parent context
•Store DOM lookup results you'll access repeatedly in variables
•Reduce the DOM Size
•Use the latest version of your framework
Eliminate jQuery class Selectors
//inefficient way to lookup for a specific classname
$('.dummyClass').doSomeManipulation();

//more efficient way, store the result in a variable
var anchors = $('#mainPanel').find('a.dummyClass');
anchors.doSomeManipulation();
Reduce the DOM Size
<body>
<form method="post" action="/about/mps-and-lords/about-lords/lpo/" id="aspnetForm">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTc3OTI0NzE5NmRk5bMcK/ttcFbAqzfJYJJ3nNI321o=" />
</div>
<div class="wrapper">
<div id="breadcrumb">
<div class="inner">
<strong>You are here:</strong>
<ul>
<li>
<a href="http://www.parliament.uk/">Parliament home page</a>
<ul>
<li>
<a href="http://www.parliament.uk/about/">About Parliament</a>
<ul>
<li>
<a href="http://www.parliament.uk/about/mps-and-lords/">About MPs, Lords &amp; officers</a>
<ul>
<li>
<a href="http://www.parliament.uk/about/mps-and-lords/about-lords/">House of Lords</a>
<ul>
<li>House of Lords Procurement</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
...
</div>
</form>
</body>
Reduce the DOM Size
<body class="main">
<form method="post" action="/about/mps-and-lords/about-lords/lpo/" id="aspnetForm" class="wrapper">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTc3OTI0NzE5NmRk5bMcK/ttcFbAqzfJYJJ3nNI321o=" />
<div id="breadcrumb">
<strong>You are here:</strong>
<ul>
<li>
<a href="http://www.parliament.uk/">Parliament home page</a>
</li>
<li>
<a href="http://www.parliament.uk/about/">About Parliament</a>
</li>
<li>
<a href="http://www.parliament.uk/about/mps-and-lords/">About MPs, Lords &amp; officers</a>
</li>
<li>
<a href="http://www.parliament.uk/about/mps-and-lords/about-lords/">House of Lords</a>
</li>
<li>House of Lords Procurement</li>
</ul>
</div>
...
</form>
</body>
Eliminate Query Waste
•Although jQuery fails nicely if it does not find any matching elements,
it still takes time to look for them
Too many XHR calls
Too many XHR calls,
requesting unnecessary data
•Don't use XHR calls within loops
•Make Ajax Cacheable - use GET for Ajax requests*
•Consider using passive requests vs. active requests
•Favour JSON over HTML or XML as your data exchange format
•Response should contain just the changed and relevant data
for the page which is being updated*

* Need some backend support
Read more here: High Performance JavaScript – chapter 7 (O’Reilly 2010)
Use predictive passive requests
Expensive DOM Manipulations
•Perform DOM manipulations off the document to minimize
DOM access
•Use strings and innerHTML property to speed up
large DOM insertions
•Batch CSS changes to minimize repaint/reflow
Expensive DOM Manipulations
//adds element to DOM and then does the manipulation
$('<div />').appendTo(someElement).doSomeManipulation();

//manipulates the element fragment before adding to the DOM
$('<div />').doSomeManipulation().appendTo(someElement);
Batch CSS changes
//inefficient way of modifying the same property
$(myElement).css(’color’, ‘red’);
currentHeight = getHeight();
$(myElement).css(’height’, currentHeight );
currentWidth = getWidth();
$(myElement).css(’width’, currentWidth);

//better way to do the same
currentHeight = getHeight();
currentWidth = getWidth();
$(myElement).css({
color: ‘red’,
height: currentHeight,
width: currentWidth
});
Leverage Event Delegation
a.k.a. event bubbling
Event Delegation
•Fewer functions to manage
•Takes up less memory
•Fewer ties between your code and the DOM
•No need to re-attach handlers after a DOM update
•Together with namespaces can consolidate all events into a nicer
centralized package
•The blur, focus, load and unload events don't bubble like other events
•mouseover and mouseout are difficult to handle via event delegation
due to their nature
Event Delegation with jQuery
•.live() provides extra functionality by walking up the DOM to match
possible ancestors
•.delegate() attaches a handler to one or more events for all elements that
match the selector, now or in the future, based on a specific set of root
elements
•event.stopPropagation() prevents the event from bubbling to ancestor
•event.stopImmediatePropagation() keeps the rest of the handlers from
being executed and prevents the event from bubbling up the DOM
Event Delegation with jQuery
//common way to add event handlers
$('.button').mouseover(function() {
$(this).addClass('hover');
}).mouseout(function() {
$(this).removeClass('hover');
});

//event delegation usage (also with event namespace)
$('#page').bind(’mouseover.buttonHover mouseout.buttonHover', function (event) {
var currentTrigger = $(event.target);
if (currentTrigger.hasClass('button')) {
event.stopPropagation();
currentTrigger.toggleClass('hover');
}
});
Defer script loading and execution
•$(document).ready occurs during page render while objects are still
downloading
•defer execution of unnecessary and runtime expensive scripts to
$(window).load event
Defer script loading and execution
$(document).ready(function () {
//execute here the scripts which are necessary
//for the page to be drawn correctly
equalHeights();
insertAjaxContent();
});
$(window).load(function () {
//execute here the scripts which can be deferred
preloadImages();
activateAccordion();
activateLightbox();
});
Questions?
Thanks
for listening
Links
•Best Practices on JavaScript and AJAX Performance

https://community.dynatrace.com/community/display/PUB/Best+Practices+on+JavaScript+and+AJA
X+Performance

•jQuery Performance Rules

http://www.artzstudio.com/2009/04/jquery-performance-rules/

•Top 10 Client-Side Performance Problems in Web 2.0

http://blog.dynatrace.com/2010/08/25/top-10-client-side-performance-problems-in-web-2-0/

•Ajax Best Practices: Reduce and Aggregate similar XHR calls

http://blog.dynatrace.com/2010/08/12/ajax-best-practices-reduce-and-aggregate-similar-xhr-calls/

•Event delegation in JavaScript

http://www.nczonline.net/blog/2009/06/30/event-delegation-in-javascript/

Mais conteúdo relacionado

Mais procurados

Windows Azure Service Bus
Windows Azure Service BusWindows Azure Service Bus
Windows Azure Service Bus
Pavel Revenkov
 
ASP.NET Scalability - WebDD
ASP.NET Scalability - WebDDASP.NET Scalability - WebDD
ASP.NET Scalability - WebDD
Phil Pursglove
 
ASP.NET Scalability - VBUG London
ASP.NET Scalability - VBUG LondonASP.NET Scalability - VBUG London
ASP.NET Scalability - VBUG London
Phil Pursglove
 

Mais procurados (20)

NGINX for Application Delivery & Acceleration
NGINX for Application Delivery & AccelerationNGINX for Application Delivery & Acceleration
NGINX for Application Delivery & Acceleration
 
Advance java session 15
Advance java session 15Advance java session 15
Advance java session 15
 
Web performance mercadolibre - ECI 2013
Web performance   mercadolibre - ECI 2013Web performance   mercadolibre - ECI 2013
Web performance mercadolibre - ECI 2013
 
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
The server side story:  Parallel and Asynchronous programming in .NET - ITPro...The server side story:  Parallel and Asynchronous programming in .NET - ITPro...
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
 
Node js
Node jsNode js
Node js
 
Benchmarking NGINX for Accuracy and Results
Benchmarking NGINX for Accuracy and ResultsBenchmarking NGINX for Accuracy and Results
Benchmarking NGINX for Accuracy and Results
 
Silverstripe at scale - design & architecture for silverstripe applications
Silverstripe at scale - design & architecture for silverstripe applicationsSilverstripe at scale - design & architecture for silverstripe applications
Silverstripe at scale - design & architecture for silverstripe applications
 
Getting Started with Web Services
Getting Started with Web ServicesGetting Started with Web Services
Getting Started with Web Services
 
MongoDB at community engine
MongoDB at community engineMongoDB at community engine
MongoDB at community engine
 
Advance java session 20
Advance java session 20Advance java session 20
Advance java session 20
 
Supporting large scale React applications
Supporting large scale React applicationsSupporting large scale React applications
Supporting large scale React applications
 
Level Up: 5 Expert Tips for Optimizing WordPress Performance
Level Up: 5 Expert Tips for Optimizing WordPress PerformanceLevel Up: 5 Expert Tips for Optimizing WordPress Performance
Level Up: 5 Expert Tips for Optimizing WordPress Performance
 
Windows Azure Service Bus
Windows Azure Service BusWindows Azure Service Bus
Windows Azure Service Bus
 
ASP.NET Scalability - WebDD
ASP.NET Scalability - WebDDASP.NET Scalability - WebDD
ASP.NET Scalability - WebDD
 
Building large scalable mission critical business applications on the web
Building large scalable mission critical business applications on the webBuilding large scalable mission critical business applications on the web
Building large scalable mission critical business applications on the web
 
Building a better web
Building a better webBuilding a better web
Building a better web
 
MongoDB London PHP
MongoDB London PHPMongoDB London PHP
MongoDB London PHP
 
ASP.NET Scalability - VBUG London
ASP.NET Scalability - VBUG LondonASP.NET Scalability - VBUG London
ASP.NET Scalability - VBUG London
 
Why Wordnik went non-relational
Why Wordnik went non-relationalWhy Wordnik went non-relational
Why Wordnik went non-relational
 
4th Lecture: JSP and such
4th Lecture:  JSP and such4th Lecture:  JSP and such
4th Lecture: JSP and such
 

Destaque (6)

Let’s practice critical thinking
Let’s practice critical thinkingLet’s practice critical thinking
Let’s practice critical thinking
 
Anatomie mobilního webu
Anatomie mobilního webuAnatomie mobilního webu
Anatomie mobilního webu
 
Proofread symbols
Proofread symbolsProofread symbols
Proofread symbols
 
Komponenty v kaskákdě
Komponenty v kaskákděKomponenty v kaskákdě
Komponenty v kaskákdě
 
HTML5 Geolocation API
HTML5 Geolocation APIHTML5 Geolocation API
HTML5 Geolocation API
 
77094122 report-on-aarong-part-two
77094122 report-on-aarong-part-two77094122 report-on-aarong-part-two
77094122 report-on-aarong-part-two
 

Semelhante a Performance optimization - Advanced techniques

#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
Justin Cataldo
 
JavaScript DOM & event
JavaScript DOM & eventJavaScript DOM & event
JavaScript DOM & event
Borey Lim
 
Ajax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesAjax Performance Tuning and Best Practices
Ajax Performance Tuning and Best Practices
Doris Chen
 
SharePoint & jQuery Guide - SPSNashville 2014
SharePoint & jQuery Guide - SPSNashville 2014SharePoint & jQuery Guide - SPSNashville 2014
SharePoint & jQuery Guide - SPSNashville 2014
Mark Rackley
 

Semelhante a Performance optimization - Advanced techniques (20)

Fast Cordova applications
Fast Cordova applicationsFast Cordova applications
Fast Cordova applications
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
 
Speeding up mobile web apps
Speeding up mobile web appsSpeeding up mobile web apps
Speeding up mobile web apps
 
The Devil and HTML5
The Devil and HTML5The Devil and HTML5
The Devil and HTML5
 
Fast mobile web apps
Fast mobile web appsFast mobile web apps
Fast mobile web apps
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
JavaScript DOM & event
JavaScript DOM & eventJavaScript DOM & event
JavaScript DOM & event
 
Break out of The Box - Part 2
Break out of The Box - Part 2Break out of The Box - Part 2
Break out of The Box - Part 2
 
AD102 - Break out of the Box
AD102 - Break out of the BoxAD102 - Break out of the Box
AD102 - Break out of the Box
 
Modern Web Technologies
Modern Web TechnologiesModern Web Technologies
Modern Web Technologies
 
5 x HTML5 worth using in APEX (5)
5 x HTML5 worth using in APEX (5)5 x HTML5 worth using in APEX (5)
5 x HTML5 worth using in APEX (5)
 
Building high performance web apps.
Building high performance web apps.Building high performance web apps.
Building high performance web apps.
 
Camel as a_glue
Camel as a_glueCamel as a_glue
Camel as a_glue
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Ajax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesAjax Performance Tuning and Best Practices
Ajax Performance Tuning and Best Practices
 
Modern JavaScript Programming
Modern JavaScript Programming Modern JavaScript Programming
Modern JavaScript Programming
 
SPTechCon DevDays - SharePoint & jQuery
SPTechCon DevDays - SharePoint & jQuerySPTechCon DevDays - SharePoint & jQuery
SPTechCon DevDays - SharePoint & jQuery
 
SharePoint & jQuery Guide - SPSNashville 2014
SharePoint & jQuery Guide - SPSNashville 2014SharePoint & jQuery Guide - SPSNashville 2014
SharePoint & jQuery Guide - SPSNashville 2014
 
SPSNH 2014 - The SharePoint & jQueryGuide
SPSNH 2014 - The SharePoint & jQueryGuideSPSNH 2014 - The SharePoint & jQueryGuide
SPSNH 2014 - The SharePoint & jQueryGuide
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

Performance optimization - Advanced techniques

  • 1. Performance optimization Front End meeting 30th June 2011 Filip Mares
  • 2. Agenda •Blocking and long running scripts •Slow CSS Selectors on IE •Too many XHR calls, requesting unnecessary data •Expensive DOM Manipulations •Leverage Event Delegation (event bubbling) •Defer script loading and execution
  • 3. Blocking and long running scripts •Improve the Time to First Impression and Time to onLoad •Script execution slows down the overall page load time •Script blocks that execute longer than 20ms have potential for improvement
  • 4. Blocking and long running scripts •First Impression great if < 1s, acceptable if < 2.5s and slow if > 2.5s •onLoad Event (DOM ready) great if < 2s, acceptable if < 4s and slow if > 4s •Fully Loaded (window load) great if < 2s, acceptable if < 5s and slow if > 5s (based on dynaTrace research)
  • 6. Eliminate jQuery class Selectors •Use Unique ID instead when possible •Specify a Tag name if you have to use the Class Name •Specify a parent context •Store DOM lookup results you'll access repeatedly in variables •Reduce the DOM Size •Use the latest version of your framework
  • 7. Eliminate jQuery class Selectors //inefficient way to lookup for a specific classname $('.dummyClass').doSomeManipulation(); //more efficient way, store the result in a variable var anchors = $('#mainPanel').find('a.dummyClass'); anchors.doSomeManipulation();
  • 8. Reduce the DOM Size <body> <form method="post" action="/about/mps-and-lords/about-lords/lpo/" id="aspnetForm"> <div> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTc3OTI0NzE5NmRk5bMcK/ttcFbAqzfJYJJ3nNI321o=" /> </div> <div class="wrapper"> <div id="breadcrumb"> <div class="inner"> <strong>You are here:</strong> <ul> <li> <a href="http://www.parliament.uk/">Parliament home page</a> <ul> <li> <a href="http://www.parliament.uk/about/">About Parliament</a> <ul> <li> <a href="http://www.parliament.uk/about/mps-and-lords/">About MPs, Lords &amp; officers</a> <ul> <li> <a href="http://www.parliament.uk/about/mps-and-lords/about-lords/">House of Lords</a> <ul> <li>House of Lords Procurement</li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </div> </div> ... </div> </form> </body>
  • 9. Reduce the DOM Size <body class="main"> <form method="post" action="/about/mps-and-lords/about-lords/lpo/" id="aspnetForm" class="wrapper"> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTc3OTI0NzE5NmRk5bMcK/ttcFbAqzfJYJJ3nNI321o=" /> <div id="breadcrumb"> <strong>You are here:</strong> <ul> <li> <a href="http://www.parliament.uk/">Parliament home page</a> </li> <li> <a href="http://www.parliament.uk/about/">About Parliament</a> </li> <li> <a href="http://www.parliament.uk/about/mps-and-lords/">About MPs, Lords &amp; officers</a> </li> <li> <a href="http://www.parliament.uk/about/mps-and-lords/about-lords/">House of Lords</a> </li> <li>House of Lords Procurement</li> </ul> </div> ... </form> </body>
  • 10. Eliminate Query Waste •Although jQuery fails nicely if it does not find any matching elements, it still takes time to look for them
  • 11. Too many XHR calls
  • 12. Too many XHR calls, requesting unnecessary data •Don't use XHR calls within loops •Make Ajax Cacheable - use GET for Ajax requests* •Consider using passive requests vs. active requests •Favour JSON over HTML or XML as your data exchange format •Response should contain just the changed and relevant data for the page which is being updated* * Need some backend support Read more here: High Performance JavaScript – chapter 7 (O’Reilly 2010)
  • 14. Expensive DOM Manipulations •Perform DOM manipulations off the document to minimize DOM access •Use strings and innerHTML property to speed up large DOM insertions •Batch CSS changes to minimize repaint/reflow
  • 15. Expensive DOM Manipulations //adds element to DOM and then does the manipulation $('<div />').appendTo(someElement).doSomeManipulation(); //manipulates the element fragment before adding to the DOM $('<div />').doSomeManipulation().appendTo(someElement);
  • 16. Batch CSS changes //inefficient way of modifying the same property $(myElement).css(’color’, ‘red’); currentHeight = getHeight(); $(myElement).css(’height’, currentHeight ); currentWidth = getWidth(); $(myElement).css(’width’, currentWidth); //better way to do the same currentHeight = getHeight(); currentWidth = getWidth(); $(myElement).css({ color: ‘red’, height: currentHeight, width: currentWidth });
  • 18. Event Delegation •Fewer functions to manage •Takes up less memory •Fewer ties between your code and the DOM •No need to re-attach handlers after a DOM update •Together with namespaces can consolidate all events into a nicer centralized package •The blur, focus, load and unload events don't bubble like other events •mouseover and mouseout are difficult to handle via event delegation due to their nature
  • 19. Event Delegation with jQuery •.live() provides extra functionality by walking up the DOM to match possible ancestors •.delegate() attaches a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements •event.stopPropagation() prevents the event from bubbling to ancestor •event.stopImmediatePropagation() keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM
  • 20. Event Delegation with jQuery //common way to add event handlers $('.button').mouseover(function() { $(this).addClass('hover'); }).mouseout(function() { $(this).removeClass('hover'); }); //event delegation usage (also with event namespace) $('#page').bind(’mouseover.buttonHover mouseout.buttonHover', function (event) { var currentTrigger = $(event.target); if (currentTrigger.hasClass('button')) { event.stopPropagation(); currentTrigger.toggleClass('hover'); } });
  • 21. Defer script loading and execution •$(document).ready occurs during page render while objects are still downloading •defer execution of unnecessary and runtime expensive scripts to $(window).load event
  • 22. Defer script loading and execution $(document).ready(function () { //execute here the scripts which are necessary //for the page to be drawn correctly equalHeights(); insertAjaxContent(); }); $(window).load(function () { //execute here the scripts which can be deferred preloadImages(); activateAccordion(); activateLightbox(); });
  • 25. Links •Best Practices on JavaScript and AJAX Performance https://community.dynatrace.com/community/display/PUB/Best+Practices+on+JavaScript+and+AJA X+Performance •jQuery Performance Rules http://www.artzstudio.com/2009/04/jquery-performance-rules/ •Top 10 Client-Side Performance Problems in Web 2.0 http://blog.dynatrace.com/2010/08/25/top-10-client-side-performance-problems-in-web-2-0/ •Ajax Best Practices: Reduce and Aggregate similar XHR calls http://blog.dynatrace.com/2010/08/12/ajax-best-practices-reduce-and-aggregate-similar-xhr-calls/ •Event delegation in JavaScript http://www.nczonline.net/blog/2009/06/30/event-delegation-in-javascript/

Notas do Editor

  1. The goal of a page must be to download all resources as fast as possible in order to improve the Time to First Impression and Time to onLoad. Long running JavaScript executed when the file is loaded cause the browser to suspend download of remaining network resources and therefore slows down the overall page load time. Script blocks that execute longer than 20ms are considered to have potential for improvement.
  2. First Impression - great if &lt; 1s, acceptable if &lt; 2.5s and slow if &gt; 2.5sThis is the time from when the URL is entered into the browser until the user has the first visual indication of the page that gets loaded. onLoad Event - great if &lt; 2s, acceptable if &lt; 4s and slow if &gt; 4sThis is the time until the browser triggers the onLoad event which happens when the initial document and all referenced objects are fully downloaded. Fully Loaded - great if &lt; 2s, acceptable if &lt; 5s and slow if &gt; 5sThis is the time until all onLoad JavaScript handlers have finished their execution and all dynamically or delay loaded content triggered by those handlers has been retrieved.
  3. As the getElementsByClassName method is missing in IE 6 and 7, frameworks like jQuery simulate this functionality by iterating through the whole DOM and checking every single DOM element whether it matches the class name of not. Depending on the size of the DOM this can become a very lengthy operation.
  4. A mistake that is often made is that too much information is fetched dynamically with too many calls. Browser only has a limited number of physical network connections it opens to each domain (2 parallel connections recommended by HTTP 1.1). When you make a lot of AJAX calls in IE 6&amp;7, the browser keeps all the requests in a queue and executes two at a time. So, if you click on something to try to navigate to another page, the browser has to wait for running calls to complete before it can take another one. JSON: lightweight, trivial to parse to a JavaScript data structure HTML: easy to inject to the page
  5. DOM manipulation is a common performance bottleneck in rich web applications. Changing the class name on the body tag causes the browser to re-evaluate all elements on the page to find out if the reflow or repaint process should re-run. A DOM tree – representation of the page structure A render tree – representation of how the DOM nodes will be displayed Repaint –When a DOM change affects the style of an element Reflow – When a DOM change affects the geometry of an element
  6. Traditional event handlers are inefficient. They can potentially cause of memory leaks and performance degradation - the more you have, the greater the risk. Event delegation improves the overall performance of large-scale web applications.
  7. If you notice your page stalling while loading, all those $(document).ready functions could be the reason why. You can reduce CPU utilization during the page load by binding your jQuery functions to the $(window).load event, which occurs after all objects called by the HTML (including &lt;iframe&gt; content) have downloaded. Functionality such as drag and drop, binding visual effects and animations, pre-fetching hidden images, etc., are all good candidates for this technique.