SlideShare a Scribd company logo
1 of 125
High Performance JavaScript Nicholas C. Zakas| CapitolJS | September 18, 2011
Who's this guy? Co-Creator csslint.net Contributor, Creator of YUI Test Ex-tech lead Yahoo! Author Lead Author Contributor Lead Author
@slicknet (complaints: @voodootikigod)
Does JavaScript performance matter?
All browsers now haveoptimizing JavaScript engines Tracemonkey/ JaegarMonkey (3.5+) V8 (all) Nitro (4+) Chakra (9+) Karakan (10.5+)
http://ie.microsoft.com/testdrive/benchmarks/sunspider/default.html
Old computers ran slow applications Small amounts of CPU power and memory
New computers are generally faster but slow applications still exist More CPU + more memory = less disciplined application development
Oh yeah, one more thing
It's still possible to write slow JavaScript
JavaScript performancedirectlyaffects user experience
The UI Threadaka Browser Event Loop
The browser UI thread is responsible for both UI updates and JavaScript execution Only one can happen at a time
Jobs for UI updates and JavaScript execution are added to a UI queue Each job must wait in line for its turn to execute
<button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button> <script type="text/javascript"> window.onload = function(){    document.getElementById("btn").onclick = function(){ //do something    }; }; </script>
Before Click UI Thread time UI Queue
When Clicked UI Thread time UI Queue UI Update onclick UI Update
When Clicked UI Thread UI Update time UI Queue onclick Draw down state UI Update
When Clicked UI Thread onclick UI Update time UI Queue UI Update
When Clicked UI Thread onclick UI Update UI Update time UI Queue Draw up state
No UI updates while JavaScript is executing
JavaScript May Cause UI Update <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button> <script type="text/javascript"> window.onload = function(){    document.getElementById("btn").onclick = function(){        var div = document.createElement(ā€œdivā€);        div.className = ā€œtipā€;        div.innerHTML = ā€œYou clicked me!ā€;        document.body.appendChild(div);    }; }; </script>
A UI update must use the latest info available
Long-running JavaScript=Unresponsive UI
Responsive UI UI Thread JavaScript UI Update UI Update time
Unresponsive UI UI Thread JavaScript UI Update UI Update time
The longer JavaScript runs,the worse the user experience
The runaway script timer prevents JavaScript from running for too long Each browser imposes its own limit (except Opera)
Internet Explorer
Firefox
Safari
Chrome
Runaway Script Timer Limits Internet Explorer: 5 million statements Firefox: 10 seconds Safari: 5 seconds Chrome: Unknown, hooks into normal crash control mechanism Opera: none
How Long Is Too Long? ā€œ0.1 second [100ms] is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.ā€ - Jakob Nielsen
Translation:No single JavaScript job should execute for more than 100ms to ensure a responsive UI
Recommendation:Limit JavaScript execution to no more than 50msmeasured on IE6 :)
Loadtime TechniquesDon't let JavaScript interfere with page load performance
During page load, JavaScript takes more time on the UI thread
<!doctype html> <html> <head>     <title>Example</title> </head> <body>     <p>Hello world!</p> <script src="foo.js"></script>     <p>See ya!</p> </body> </html>
Result UI Thread JavaScript UI Update UI Update time
Result UI Thread foo.js See ya! Hello world! time
Result UI Thread Download See ya! Hello world! Parse Run time The UI thread needs to wait for the script to download, parse, and run before continuing
Result UI Thread Download See ya! Hello world! Parse Run Variable Constant Download time takes the longest and is variable
Translation:The page doesn't render while JavaScript is downloading, parsing, or executing during page load
<!doctype html> <html> <head>     <title>Example</title> </head> <body> <script src="foo.js"></script>     <p>Hello world!</p> <script src="bar.js"></script>     <p>See ya!</p> <script src="baz.js"></script>     <p>Uh oh!</p> </body> </html>
Result UI Thread JavaScript UI Update UI Update JavaScript JavaScript time The more scripts to download in between UI updates, the longer the page takes to render
Technique #1: Load scripts dynamically
Basic Technique var script = document.createElement("script"),     body; script.type = "text/javascript"; script.src = "foo.js"; body.insertBefore(script, body.firstChild); Dynamically loaded scripts are non-blocking
Downloads no longer block the UI thread
<!doctype html> <html> <head>     <title>Example</title> </head> <body>     <p>Hello world!</p> <script src="foo.js"></script>     <p>See ya!</p> </body> </html>
Using HTML <script> UI Thread Download See ya! Hello world! Parse Run time
<!doctype html> <html> <head>     <title>Example</title> </head> <body>     <p>Hello world!</p>     <script>     var script = document.createElement("script"),         body = document.body;     script.type = "text/javascript";     script.src = "foo.js";     body.insertBefore(script, body.firstChild);     </script>     <p>See ya!</p><!-- more content --> </body> </html>
Using Dynamic Scripts UI Thread See ya! Hello world! UI Update Run time Download Parse Only code execution happens on the UI thread, which means less blocking of UI updates
function loadScript(url, callback){var script = document.createElement("script"),    body = document.body;script.type = "text/javascript"; if (script.readyState){  //IE <= 8    script.onreadystatechange = function(){if (script.readyState == "loaded" ||                script.readyState == "complete"){            script.onreadystatechange = null;            callback();        }    };} else {  //Others    script.onload = function(){        callback();    };}script.src = url;body.insertBefore(script, body.firstChild); }
Usage loadScript("foo.js", function(){     alert("Loaded!"); });
Timing Note:Script execution begins immediately after download and parse ā€“ timing of execution is not guaranteed
Technique #2: Defer scripts
<!doctype html> <html> <head>     <title>Example</title> </head> <body>     <p>Hello world!</p> <script defer src="foo.js"></script>     <p>See ya!</p>     <!-- even more markup --> </body> </html>
Support for <script defer> ? 5.0 3.5 7.0 4.0
Deferred scripts begin to download immediately, but don't execute until all UI updates complete
Using <script defer> UI Thread See ya! Hello world! More UI Run More UI time Download Parse Similar to dynamic script nodes, but with a guarantee that execution will happen last
Timing Note:Although scripts always execute after UI updates complete, the order of multiple <script defer> scripts is not guaranteed across browsers
Technique #3: Asynchronous scripts
<!doctype html> <html> <head>     <title>Example</title> </head> <body>     <p>Hello world!</p> <script async src="foo.js"></script>     <p>See ya!</p>     <!-- even more markup --> </body> </html>
Support for <script async> ? 5.0 3.6 7.0 10
Asynchronous scripts behave a lot like dynamic scripts
Using <script async> UI Thread See ya! Hello world! UI Update Run time Download Parse Download begins immediately and execution is slotted in at first available spot
Note:Order of execution is explicitly not preserved for asynchronous scripts
Runtime TechniquesWays to ensure JavaScript doesn't run away
function processArray(items, process, callback){ for (var i=0,len=items.length; i < len; i++){         process(items[i]);     }     callback(); }
Technique #1: Timers
//create a new timer and delay by 500ms setTimeout(function(){ //code to execute here }, 500); setTimeout() schedules a function to be added to the UI queue after a delay
function timedProcessArray(items, process, callback){ //create a clone of the original  var todo = items.concat();     setTimeout(function(){ var start = +new Date(); do {             process(todo.shift());         } while (todo.length > 0 &&              (+new Date() - start < 50)); if (todo.length > 0){             setTimeout(arguments.callee, 25);         } else {             callback(items);         }     }, 25); }
When Clicked UI Thread time UI Queue UI Update onclick UI Update
When Clicked UI Thread UI Update time UI Queue onclick UI Update
When Clicked UI Thread onclick UI Update time UI Queue UI Update
When Clicked UI Thread UI Update UI Update onclick time UI Queue
After 25ms UI Thread UI Update UI Update onclick time UI Queue JavaScript
After 25ms UI Thread JavaScript UI Update UI Update onclick time UI Queue
After Another 25ms UI Thread JavaScript UI Update UI Update onclick time UI Queue JavaScript
After Another 25ms UI Thread JavaScript JavaScript UI Update UI Update onclick time UI Queue
Technique #2: Script Yielding NEW!
//delay a function until after UI updates are done setImmediate(function(){ //code to execute here }); setImmediate() adds code to the UI queue after pending UI updates are finished
Support for Script Yielding ? ? ? ? 10 msSetIntermediate()
functionyieldingProcessArray(items, process, callback){ //create a clone of the originalvartodo = items.concat(); setImmediate(function(){ var start = +new Date(); do {             process(todo.shift());         } while (todo.length > 0 &&              (+new Date() - start < 50)); if (todo.length > 0){ setImmediate(arguments.callee);         } else {             callback(items);         } }); }
When Clicked UI Thread time UI Queue UI Update onclick UI Update
When Clicked UI Thread UI Update time UI Queue onclick UI Update
When Clicked UI Thread onclick UI Update time UI Queue UI Update
When Clicked UI Thread UI Update UI Update onclick time UI Queue
After Last UI Update UI Thread UI Update UI Update onclick time UI Queue JavaScript
After Last UI Update UI Thread JavaScript UI Update UI Update onclick time UI Queue
No Other UI Updates UI Thread JavaScript UI Update UI Update onclick time UI Queue JavaScript
No Other UI Updates UI Thread JavaScript JavaScript UI Update UI Update onclick time UI Queue
Technique #3: Web Workers
Support for Web Workers 10.6 4.0 3.5 4.0 10
Web Workers Asynchronous JavaScript execution Execution happens outside the UI thread Doesnā€™t block UI updates Data-Driven API Data is serialized going into and out of the worker No access to DOM or BOM Separate execution environment
//in page var worker = new Worker("process.js"); worker.onmessage = function(event){     useData(event.data); }; worker.postMessage(values); //in process.js self.onmessage = function(event){ var items = event.data; for (var i=0,len=items.length; i < len; i++){         process(items[i]);     }     self.postMessage(items); };
When Clicked UI Thread time UI Queue UI Update onclick UI Update
When Clicked UI Thread UI Update time UI Queue onclick UI Update
When Clicked UI Thread onclick UI Update time UI Queue UI Update
When Clicked UI Thread onclick UI Update time UI Queue Worker Thread UI Update
When Clicked UI Thread UI Update UI Update onclick time UI Queue Worker Thread JavaScript
Worker Thread Complete UI Thread UI Update UI Update onclick time UI Queue onmessage
Worker Thread Complete UI Thread onmessage UI Update UI Update onclick time UI Queue
Recap
The browser UI thread is responsible for both UI updates and JavaScript execution Only one can happen at a time
Responsive UI UI Thread JavaScript UI Update UI Update time
Unresponsive UI UI Thread JavaScript UI Update UI Update time
Avoid Slow Loading JavaScript Dynamically created scripts Deferred scripts Asynchronous scripts
Avoid Slow JavaScript Don't allow JavaScript to execute for more than 50ms Break up long JavaScript processes using: Timers Script Yielding (future) Web Workers
Etcetera My blog: 	www.nczonline.net Twitter:		@slicknet These Slides:	slideshare.net/nzakas Hire us:		projects@stubbornella.org
Questions?
Creative Commons Images Used http://www.flickr.com/photos/lrargerich/3115367361/ http://www.flickr.com/photos/hippie/2406411610/ http://www.flickr.com/photos/55733754@N00/3325000738/ http://www.flickr.com/photos/eurleif/255241547/ http://www.flickr.com/photos/off_the_wall/3444915939/ http://www.flickr.com/photos/wwarby/3296379139/ http://www.flickr.com/photos/derekgavey/4358797365/ http://www.flickr.com/photos/mulad/286641998/ http://www.flickr.com/photos/torley/2361164281/ http://www.flickr.com/photos/ottoman42/455242/ http://www.flickr.com/photos/goincase/3843348908/

More Related Content

What's hot

Browser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom Menace
Nicholas Zakas
Ā 
JavaScript Libraries: The Big Picture
JavaScript Libraries: The Big PictureJavaScript Libraries: The Big Picture
JavaScript Libraries: The Big Picture
Simon Willison
Ā 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
Julien Lecomte
Ā 
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and PerformanceJavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
Nicholas Zakas
Ā 
AngularJS for Legacy Apps
AngularJS for Legacy AppsAngularJS for Legacy Apps
AngularJS for Legacy Apps
Peter Drinnan
Ā 

What's hot (20)

High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011
Ā 
Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)
Ā 
Mobile Web Speed Bumps
Mobile Web Speed BumpsMobile Web Speed Bumps
Mobile Web Speed Bumps
Ā 
WordPress and Ajax
WordPress and AjaxWordPress and Ajax
WordPress and Ajax
Ā 
Browser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom Menace
Ā 
High Performance Snippets
High Performance SnippetsHigh Performance Snippets
High Performance Snippets
Ā 
Don't make me wait! or Building High-Performance Web Applications
Don't make me wait! or Building High-Performance Web ApplicationsDon't make me wait! or Building High-Performance Web Applications
Don't make me wait! or Building High-Performance Web Applications
Ā 
Building an HTML5 Video Player
Building an HTML5 Video PlayerBuilding an HTML5 Video Player
Building an HTML5 Video Player
Ā 
Ajax Security
Ajax SecurityAjax Security
Ajax Security
Ā 
Testing Mobile JavaScript
Testing Mobile JavaScriptTesting Mobile JavaScript
Testing Mobile JavaScript
Ā 
JavaScript Libraries: The Big Picture
JavaScript Libraries: The Big PictureJavaScript Libraries: The Big Picture
JavaScript Libraries: The Big Picture
Ā 
Fav
FavFav
Fav
Ā 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
Ā 
Tek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJSTek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJS
Ā 
jQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksjQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & Tricks
Ā 
How to Develop a Rich, Native-quality User Experience for Mobile Using Web St...
How to Develop a Rich, Native-quality User Experience for Mobile Using Web St...How to Develop a Rich, Native-quality User Experience for Mobile Using Web St...
How to Develop a Rich, Native-quality User Experience for Mobile Using Web St...
Ā 
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and PerformanceJavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
Ā 
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Ā 
AngularJS for Legacy Apps
AngularJS for Legacy AppsAngularJS for Legacy Apps
AngularJS for Legacy Apps
Ā 
High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)
Ā 

Viewers also liked

JavaScript APIs youā€™ve never heard of (and some you have)
JavaScript APIs youā€™ve never heard of (and some you have)JavaScript APIs youā€™ve never heard of (and some you have)
JavaScript APIs youā€™ve never heard of (and some you have)
Nicholas Zakas
Ā 
8051 Timers / Counters
8051 Timers / Counters8051 Timers / Counters
8051 Timers / Counters
Patricio Lima
Ā 
Excellence land rover
Excellence land roverExcellence land rover
Excellence land rover
nirmal francis
Ā 
srthsrth
srthsrthsrthsrth
srthsrth
nn2141485
Ā 
Proactive Professionalism Networking Today Nj 1
Proactive Professionalism Networking Today Nj 1Proactive Professionalism Networking Today Nj 1
Proactive Professionalism Networking Today Nj 1
Suzanne Carbonaro
Ā 
Good prescribing
Good prescribingGood prescribing
Good prescribing
Resti Cahyani
Ā 

Viewers also liked (20)

Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
Ā 
JavaScript APIs youā€™ve never heard of (and some you have)
JavaScript APIs youā€™ve never heard of (and some you have)JavaScript APIs youā€™ve never heard of (and some you have)
JavaScript APIs youā€™ve never heard of (and some you have)
Ā 
Writing Efficient JavaScript
Writing Efficient JavaScriptWriting Efficient JavaScript
Writing Efficient JavaScript
Ā 
High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010
Ā 
Timers and pwm
Timers and pwmTimers and pwm
Timers and pwm
Ā 
Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)
Ā 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
Ā 
Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!
Ā 
8051 Timers / Counters
8051 Timers / Counters8051 Timers / Counters
8051 Timers / Counters
Ā 
Extreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI CompressorExtreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI Compressor
Ā 
Excellence land rover
Excellence land roverExcellence land rover
Excellence land rover
Ā 
Mt on leadership and its effects on employees performance
Mt on   leadership and its effects on employees performanceMt on   leadership and its effects on employees performance
Mt on leadership and its effects on employees performance
Ā 
Report..costing..
Report..costing..Report..costing..
Report..costing..
Ā 
srthsrth
srthsrthsrthsrth
srthsrth
Ā 
Ghgfhgfh
GhgfhgfhGhgfhgfh
Ghgfhgfh
Ā 
nullcon 2011 - Buffer UnderRun Exploits
nullcon 2011 - Buffer UnderRun Exploitsnullcon 2011 - Buffer UnderRun Exploits
nullcon 2011 - Buffer UnderRun Exploits
Ā 
Proactive Professionalism Networking Today Nj 1
Proactive Professionalism Networking Today Nj 1Proactive Professionalism Networking Today Nj 1
Proactive Professionalism Networking Today Nj 1
Ā 
Transactional learning and simulations: how far can we go in professional leg...
Transactional learning and simulations: how far can we go in professional leg...Transactional learning and simulations: how far can we go in professional leg...
Transactional learning and simulations: how far can we go in professional leg...
Ā 
Prescrition co-owners- pdf
Prescrition   co-owners- pdfPrescrition   co-owners- pdf
Prescrition co-owners- pdf
Ā 
Good prescribing
Good prescribingGood prescribing
Good prescribing
Ā 

Similar to High Performance JavaScript (CapitolJS 2011)

Responsive interfaces
Responsive interfacesResponsive interfaces
Responsive interfaces
Nicholas Zakas
Ā 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
Adil Jafri
Ā 
GoogleåœØWeb前ē«Æę–¹é¢ēš„ē»éŖŒ
GoogleåœØWeb前ē«Æę–¹é¢ēš„ē»éŖŒGoogleåœØWeb前ē«Æę–¹é¢ēš„ē»éŖŒ
GoogleåœØWeb前ē«Æę–¹é¢ēš„ē»éŖŒ
yiditushe
Ā 
Sxsw 20090314
Sxsw 20090314Sxsw 20090314
Sxsw 20090314
guestcabcf63
Ā 
Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
Ā 
Wookie Meetup
Wookie MeetupWookie Meetup
Wookie Meetup
scottw
Ā 
Wookie Meetup
Wookie MeetupWookie Meetup
Wookie Meetup
scottw
Ā 

Similar to High Performance JavaScript (CapitolJS 2011) (20)

Responsive interfaces
Responsive interfacesResponsive interfaces
Responsive interfaces
Ā 
Even Faster Web Sites at jQuery Conference '09
Even Faster Web Sites at jQuery Conference '09Even Faster Web Sites at jQuery Conference '09
Even Faster Web Sites at jQuery Conference '09
Ā 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupal
Ā 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
Ā 
JavaScript Performance Patterns
JavaScript Performance PatternsJavaScript Performance Patterns
JavaScript Performance Patterns
Ā 
J Query Presentation
J Query PresentationJ Query Presentation
J Query Presentation
Ā 
Basic testing with selenium
Basic testing with seleniumBasic testing with selenium
Basic testing with selenium
Ā 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
Ā 
Selenium
SeleniumSelenium
Selenium
Ā 
Rapid JCR Applications Development with Sling
Rapid JCR Applications Development with SlingRapid JCR Applications Development with Sling
Rapid JCR Applications Development with Sling
Ā 
Accelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Accelerated Adoption: HTML5 and CSS3 for ASP.NET DevelopersAccelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Accelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Ā 
GoogleåœØWeb前ē«Æę–¹é¢ēš„ē»éŖŒ
GoogleåœØWeb前ē«Æę–¹é¢ēš„ē»éŖŒGoogleåœØWeb前ē«Æę–¹é¢ēš„ē»éŖŒ
GoogleåœØWeb前ē«Æę–¹é¢ēš„ē»éŖŒ
Ā 
SXSW: Even Faster Web Sites
SXSW: Even Faster Web SitesSXSW: Even Faster Web Sites
SXSW: Even Faster Web Sites
Ā 
Sxsw 20090314
Sxsw 20090314Sxsw 20090314
Sxsw 20090314
Ā 
Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011
Ā 
Node js presentation
Node js presentationNode js presentation
Node js presentation
Ā 
Wookie Meetup
Wookie MeetupWookie Meetup
Wookie Meetup
Ā 
Wookie Meetup
Wookie MeetupWookie Meetup
Wookie Meetup
Ā 
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
WebTest - Efficient Functional Web Testing with HtmlUnit and BeyondWebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
Ā 
Performance on the Yahoo! Homepage
Performance on the Yahoo! HomepagePerformance on the Yahoo! Homepage
Performance on the Yahoo! Homepage
Ā 

More from Nicholas Zakas

More from Nicholas Zakas (11)

The Pointerless Web
The Pointerless WebThe Pointerless Web
The Pointerless Web
Ā 
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
Ā 
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Ā 
YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)
Ā 
Nicholas' Performance Talk at Google
Nicholas' Performance Talk at GoogleNicholas' Performance Talk at Google
Nicholas' Performance Talk at Google
Ā 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
Ā 
Speed Up Your JavaScript
Speed Up Your JavaScriptSpeed Up Your JavaScript
Speed Up Your JavaScript
Ā 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScript
Ā 
JavaScript Variable Performance
JavaScript Variable PerformanceJavaScript Variable Performance
JavaScript Variable Performance
Ā 
The New Yahoo! Homepage and YUI 3
The New Yahoo! Homepage and YUI 3The New Yahoo! Homepage and YUI 3
The New Yahoo! Homepage and YUI 3
Ā 
Test Driven Development With YUI Test (Ajax Experience 2008)
Test Driven Development With YUI Test (Ajax Experience 2008)Test Driven Development With YUI Test (Ajax Experience 2008)
Test Driven Development With YUI Test (Ajax Experience 2008)
Ā 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
Ā 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
Ā 

Recently uploaded (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
Ā 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
Ā 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
Ā 
šŸ¬ The future of MySQL is Postgres šŸ˜
šŸ¬  The future of MySQL is Postgres   šŸ˜šŸ¬  The future of MySQL is Postgres   šŸ˜
šŸ¬ The future of MySQL is Postgres šŸ˜
Ā 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
Ā 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Ā 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
Ā 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
Ā 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
Ā 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Ā 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
Ā 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
Ā 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
Ā 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
Ā 
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
Ā 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Ā 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
Ā 
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
Ā 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
Ā 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Ā 

High Performance JavaScript (CapitolJS 2011)

  • 1. High Performance JavaScript Nicholas C. Zakas| CapitolJS | September 18, 2011
  • 2. Who's this guy? Co-Creator csslint.net Contributor, Creator of YUI Test Ex-tech lead Yahoo! Author Lead Author Contributor Lead Author
  • 5.
  • 6.
  • 7.
  • 8. All browsers now haveoptimizing JavaScript engines Tracemonkey/ JaegarMonkey (3.5+) V8 (all) Nitro (4+) Chakra (9+) Karakan (10.5+)
  • 10. Old computers ran slow applications Small amounts of CPU power and memory
  • 11. New computers are generally faster but slow applications still exist More CPU + more memory = less disciplined application development
  • 12.
  • 13. Oh yeah, one more thing
  • 14.
  • 15.
  • 16.
  • 17. It's still possible to write slow JavaScript
  • 19. The UI Threadaka Browser Event Loop
  • 20. The browser UI thread is responsible for both UI updates and JavaScript execution Only one can happen at a time
  • 21. Jobs for UI updates and JavaScript execution are added to a UI queue Each job must wait in line for its turn to execute
  • 22. <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button> <script type="text/javascript"> window.onload = function(){ document.getElementById("btn").onclick = function(){ //do something }; }; </script>
  • 23. Before Click UI Thread time UI Queue
  • 24. When Clicked UI Thread time UI Queue UI Update onclick UI Update
  • 25. When Clicked UI Thread UI Update time UI Queue onclick Draw down state UI Update
  • 26. When Clicked UI Thread onclick UI Update time UI Queue UI Update
  • 27. When Clicked UI Thread onclick UI Update UI Update time UI Queue Draw up state
  • 28. No UI updates while JavaScript is executing
  • 29. JavaScript May Cause UI Update <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button> <script type="text/javascript"> window.onload = function(){ document.getElementById("btn").onclick = function(){ var div = document.createElement(ā€œdivā€); div.className = ā€œtipā€; div.innerHTML = ā€œYou clicked me!ā€; document.body.appendChild(div); }; }; </script>
  • 30. A UI update must use the latest info available
  • 32. Responsive UI UI Thread JavaScript UI Update UI Update time
  • 33. Unresponsive UI UI Thread JavaScript UI Update UI Update time
  • 34. The longer JavaScript runs,the worse the user experience
  • 35. The runaway script timer prevents JavaScript from running for too long Each browser imposes its own limit (except Opera)
  • 40.
  • 41. Runaway Script Timer Limits Internet Explorer: 5 million statements Firefox: 10 seconds Safari: 5 seconds Chrome: Unknown, hooks into normal crash control mechanism Opera: none
  • 42. How Long Is Too Long? ā€œ0.1 second [100ms] is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.ā€ - Jakob Nielsen
  • 43. Translation:No single JavaScript job should execute for more than 100ms to ensure a responsive UI
  • 44. Recommendation:Limit JavaScript execution to no more than 50msmeasured on IE6 :)
  • 45. Loadtime TechniquesDon't let JavaScript interfere with page load performance
  • 46. During page load, JavaScript takes more time on the UI thread
  • 47. <!doctype html> <html> <head> <title>Example</title> </head> <body> <p>Hello world!</p> <script src="foo.js"></script> <p>See ya!</p> </body> </html>
  • 48. Result UI Thread JavaScript UI Update UI Update time
  • 49. Result UI Thread foo.js See ya! Hello world! time
  • 50. Result UI Thread Download See ya! Hello world! Parse Run time The UI thread needs to wait for the script to download, parse, and run before continuing
  • 51. Result UI Thread Download See ya! Hello world! Parse Run Variable Constant Download time takes the longest and is variable
  • 52. Translation:The page doesn't render while JavaScript is downloading, parsing, or executing during page load
  • 53. <!doctype html> <html> <head> <title>Example</title> </head> <body> <script src="foo.js"></script> <p>Hello world!</p> <script src="bar.js"></script> <p>See ya!</p> <script src="baz.js"></script> <p>Uh oh!</p> </body> </html>
  • 54. Result UI Thread JavaScript UI Update UI Update JavaScript JavaScript time The more scripts to download in between UI updates, the longer the page takes to render
  • 55. Technique #1: Load scripts dynamically
  • 56. Basic Technique var script = document.createElement("script"), body; script.type = "text/javascript"; script.src = "foo.js"; body.insertBefore(script, body.firstChild); Dynamically loaded scripts are non-blocking
  • 57. Downloads no longer block the UI thread
  • 58. <!doctype html> <html> <head> <title>Example</title> </head> <body> <p>Hello world!</p> <script src="foo.js"></script> <p>See ya!</p> </body> </html>
  • 59. Using HTML <script> UI Thread Download See ya! Hello world! Parse Run time
  • 60. <!doctype html> <html> <head> <title>Example</title> </head> <body> <p>Hello world!</p> <script> var script = document.createElement("script"), body = document.body; script.type = "text/javascript"; script.src = "foo.js"; body.insertBefore(script, body.firstChild); </script> <p>See ya!</p><!-- more content --> </body> </html>
  • 61. Using Dynamic Scripts UI Thread See ya! Hello world! UI Update Run time Download Parse Only code execution happens on the UI thread, which means less blocking of UI updates
  • 62. function loadScript(url, callback){var script = document.createElement("script"), body = document.body;script.type = "text/javascript"; if (script.readyState){ //IE <= 8 script.onreadystatechange = function(){if (script.readyState == "loaded" || script.readyState == "complete"){ script.onreadystatechange = null; callback(); } };} else { //Others script.onload = function(){ callback(); };}script.src = url;body.insertBefore(script, body.firstChild); }
  • 63. Usage loadScript("foo.js", function(){ alert("Loaded!"); });
  • 64. Timing Note:Script execution begins immediately after download and parse ā€“ timing of execution is not guaranteed
  • 66. <!doctype html> <html> <head> <title>Example</title> </head> <body> <p>Hello world!</p> <script defer src="foo.js"></script> <p>See ya!</p> <!-- even more markup --> </body> </html>
  • 67. Support for <script defer> ? 5.0 3.5 7.0 4.0
  • 68. Deferred scripts begin to download immediately, but don't execute until all UI updates complete
  • 69. Using <script defer> UI Thread See ya! Hello world! More UI Run More UI time Download Parse Similar to dynamic script nodes, but with a guarantee that execution will happen last
  • 70. Timing Note:Although scripts always execute after UI updates complete, the order of multiple <script defer> scripts is not guaranteed across browsers
  • 72. <!doctype html> <html> <head> <title>Example</title> </head> <body> <p>Hello world!</p> <script async src="foo.js"></script> <p>See ya!</p> <!-- even more markup --> </body> </html>
  • 73. Support for <script async> ? 5.0 3.6 7.0 10
  • 74. Asynchronous scripts behave a lot like dynamic scripts
  • 75. Using <script async> UI Thread See ya! Hello world! UI Update Run time Download Parse Download begins immediately and execution is slotted in at first available spot
  • 76. Note:Order of execution is explicitly not preserved for asynchronous scripts
  • 77. Runtime TechniquesWays to ensure JavaScript doesn't run away
  • 78. function processArray(items, process, callback){ for (var i=0,len=items.length; i < len; i++){ process(items[i]); } callback(); }
  • 80. //create a new timer and delay by 500ms setTimeout(function(){ //code to execute here }, 500); setTimeout() schedules a function to be added to the UI queue after a delay
  • 81. function timedProcessArray(items, process, callback){ //create a clone of the original var todo = items.concat(); setTimeout(function(){ var start = +new Date(); do { process(todo.shift()); } while (todo.length > 0 && (+new Date() - start < 50)); if (todo.length > 0){ setTimeout(arguments.callee, 25); } else { callback(items); } }, 25); }
  • 82. When Clicked UI Thread time UI Queue UI Update onclick UI Update
  • 83. When Clicked UI Thread UI Update time UI Queue onclick UI Update
  • 84. When Clicked UI Thread onclick UI Update time UI Queue UI Update
  • 85. When Clicked UI Thread UI Update UI Update onclick time UI Queue
  • 86. After 25ms UI Thread UI Update UI Update onclick time UI Queue JavaScript
  • 87. After 25ms UI Thread JavaScript UI Update UI Update onclick time UI Queue
  • 88. After Another 25ms UI Thread JavaScript UI Update UI Update onclick time UI Queue JavaScript
  • 89. After Another 25ms UI Thread JavaScript JavaScript UI Update UI Update onclick time UI Queue
  • 90. Technique #2: Script Yielding NEW!
  • 91.
  • 92. //delay a function until after UI updates are done setImmediate(function(){ //code to execute here }); setImmediate() adds code to the UI queue after pending UI updates are finished
  • 93. Support for Script Yielding ? ? ? ? 10 msSetIntermediate()
  • 94. functionyieldingProcessArray(items, process, callback){ //create a clone of the originalvartodo = items.concat(); setImmediate(function(){ var start = +new Date(); do { process(todo.shift()); } while (todo.length > 0 && (+new Date() - start < 50)); if (todo.length > 0){ setImmediate(arguments.callee); } else { callback(items); } }); }
  • 95. When Clicked UI Thread time UI Queue UI Update onclick UI Update
  • 96. When Clicked UI Thread UI Update time UI Queue onclick UI Update
  • 97. When Clicked UI Thread onclick UI Update time UI Queue UI Update
  • 98. When Clicked UI Thread UI Update UI Update onclick time UI Queue
  • 99. After Last UI Update UI Thread UI Update UI Update onclick time UI Queue JavaScript
  • 100. After Last UI Update UI Thread JavaScript UI Update UI Update onclick time UI Queue
  • 101. No Other UI Updates UI Thread JavaScript UI Update UI Update onclick time UI Queue JavaScript
  • 102. No Other UI Updates UI Thread JavaScript JavaScript UI Update UI Update onclick time UI Queue
  • 103. Technique #3: Web Workers
  • 104.
  • 105. Support for Web Workers 10.6 4.0 3.5 4.0 10
  • 106. Web Workers Asynchronous JavaScript execution Execution happens outside the UI thread Doesnā€™t block UI updates Data-Driven API Data is serialized going into and out of the worker No access to DOM or BOM Separate execution environment
  • 107. //in page var worker = new Worker("process.js"); worker.onmessage = function(event){ useData(event.data); }; worker.postMessage(values); //in process.js self.onmessage = function(event){ var items = event.data; for (var i=0,len=items.length; i < len; i++){ process(items[i]); } self.postMessage(items); };
  • 108. When Clicked UI Thread time UI Queue UI Update onclick UI Update
  • 109. When Clicked UI Thread UI Update time UI Queue onclick UI Update
  • 110. When Clicked UI Thread onclick UI Update time UI Queue UI Update
  • 111. When Clicked UI Thread onclick UI Update time UI Queue Worker Thread UI Update
  • 112. When Clicked UI Thread UI Update UI Update onclick time UI Queue Worker Thread JavaScript
  • 113. Worker Thread Complete UI Thread UI Update UI Update onclick time UI Queue onmessage
  • 114. Worker Thread Complete UI Thread onmessage UI Update UI Update onclick time UI Queue
  • 115. Recap
  • 116. The browser UI thread is responsible for both UI updates and JavaScript execution Only one can happen at a time
  • 117. Responsive UI UI Thread JavaScript UI Update UI Update time
  • 118. Unresponsive UI UI Thread JavaScript UI Update UI Update time
  • 119. Avoid Slow Loading JavaScript Dynamically created scripts Deferred scripts Asynchronous scripts
  • 120. Avoid Slow JavaScript Don't allow JavaScript to execute for more than 50ms Break up long JavaScript processes using: Timers Script Yielding (future) Web Workers
  • 121.
  • 122.
  • 123. Etcetera My blog: www.nczonline.net Twitter: @slicknet These Slides: slideshare.net/nzakas Hire us: projects@stubbornella.org
  • 125. Creative Commons Images Used http://www.flickr.com/photos/lrargerich/3115367361/ http://www.flickr.com/photos/hippie/2406411610/ http://www.flickr.com/photos/55733754@N00/3325000738/ http://www.flickr.com/photos/eurleif/255241547/ http://www.flickr.com/photos/off_the_wall/3444915939/ http://www.flickr.com/photos/wwarby/3296379139/ http://www.flickr.com/photos/derekgavey/4358797365/ http://www.flickr.com/photos/mulad/286641998/ http://www.flickr.com/photos/torley/2361164281/ http://www.flickr.com/photos/ottoman42/455242/ http://www.flickr.com/photos/goincase/3843348908/

Editor's Notes

  1. Over the past couple of years, we&apos;ve seen JavaScript development earn recognition as a true discipline. The idea that you should architect your code, use patterns and good programming practices has really elevated the role of the front end engineer. In my opinion, part of this elevation has been the adoption of what has traditionally been considered back end methodologies. We now focus on performance and algorithms, there&apos;s unit testing for JavaScript, and so much more. One of the areas that I&apos;ve seen a much slower than adoption that I&apos;d like is in the area of error handling.How many people have an error handling strategy for their backend? How many have dashboards that display problems with uptime and performance? How many have anything similar for the front end?Typically, the front end has been this black hole of information. You may get a few customer reports here and there, but you have no information about what&apos;s going on, how often it&apos;s occurring, or how many people have been affected.
  2. So what have we talked about? Maintainable JavaScript is made up of four components.First is Code Conventions that describe the format of the code youā€™re writing.Second is Loose Coupling ā€“ keeping HTML, JavaScript, and CSS on separate layers and keeping application logic out of event handlers.Third is Programming Practices that ensure your code is readable and easily debugged.Fourth is creating a Build Process