SlideShare a Scribd company logo
High Performance JavaScript
                                   Nicholas C. Zakas
                Principal Front End Engineer, Yahoo!
     jQuery Conference – SF Bay Area, April 24 2010
Principal Front End Engineer
Contributor
Author
Things I Know About
                                  JavaScript
                   Professional
                    Wrestling



            YUI




jQuery
Does this matter?
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
It's still possible to write slow
JavaScript on the new, faster
       JavaScript engines
How can I improve JavaScript
       performance?
How can I improve JavaScript
       performance?
How can I make this fast???
How can I improve JavaScript
       performance?
How can I make this fast???

  Why is this so slow?????
Many aspects conspire to make JavaScript slow
           Awareness is the first step to solution
The UI Thread
The brains of the operation
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 if the UI thread is busy
         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">
$(document).ready(function(){
    $("#btn").bind("click",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

 UI Update   onclick

time
                              UI Queue

                                UI Update
When Clicked

UI Thread

 UI Update   onclick       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">
$(document).ready(function(){
   $("#btn").bind("click",function(){
        $("body").append("<div class="tip">You " +
                         "clicked me!</div>”);
    });
});
</script>
A UI update must use the latest
        info available
Long-running JavaScript
          =
   Unresponsive UI
Responsive UI

UI Thread

 UI Update   JavaScript   UI Update

time
Unresponsive UI

UI Thread

 UI Update       JavaScript    UI Update

time
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 50ms
function processArray(items, process, callback){
    for (var i=0,len=items.length; i < len; i++){
        process(items[i]);
    }
    callback();
}
Timers to the rescue!
JavaScript Timers
• Created using setTimeout()
• Schedules a new JavaScript execution job for
  some time in the future
• When the delay is up, the job is added to the
  UI queue
   – Note: This does not guarantee execution
     after the delay, just that the job is added
     to the UI queue and will be executed when
     appropriate
JavaScript Timers
• For complex processing, split up into timed
  functionality
• Use timers to delay some processing for later
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

 UI Update   onclick




time
                                  UI Queue

                                    UI Update
When Clicked

UI Thread

 UI Update   onclick   UI Update

time
                                   UI Queue
After 25ms

UI Thread

 UI Update   onclick   UI Update

time
                                    UI Queue

                                      JavaScript
After 25ms

UI Thread

 UI Update   onclick   UI Update   JavaScript




time
                                                UI Queue
After Another 25ms

UI Thread

 UI Update   onclick   UI Update   JavaScript




time
                                                UI Queue

                                                  JavaScript
After Another 25ms

UI Thread

 UI Update   onclick   UI Update   JavaScript         JavaScript




time
                                                UI Queue
Web Workers to the rescue!
Web Workers
• Asynchronous JavaScript execution
• Execution happens in a separate process
   – Not on the UI thread = no UI delays
• Data-driven API
   – Data is serialized when sending data into
     or out of Worker
   – No access to DOM, BOM
   – Completely 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

 UI Update   onclick




time
                                  UI Queue

                                    UI Update
When Clicked

UI Thread

 UI Update   onclick




time

             Worker Thread        UI Queue

                                    UI Update
When Clicked

UI Thread

 UI Update   onclick       UI Update

time

             Worker Thread             UI Queue

                       JavaScript
Worker Thread Complete

UI Thread

 UI Update    onclick   UI Update

time
                                    UI Queue

                                     onmessage
Worker Thread Complete

UI Thread

 UI Update    onclick   UI Update   onmessage




time
                                           UI Queue
Web Workers Support




3.5      4.0        4.0
Repaint and Reflow
     UI update jobs
Long UI updates
       =
Unresponsive UI
Unresponsive UI

UI Thread

 UI Update   JavaScript   UI Update

time
Long UI updates
       =
Unresponsive UI
       =
Frustrated users
JavaScript can cause
  long UI updates
A repaint occurs when a visual change doesn't
        require recalculation of layout
 Changes to visibility, colors (text/background), background images, etc.
Repaint
<button id="btn" style="font-size: 30px; padding: 0.5em
    1em">Click Me</button>

<script type="text/javascript">
$(document).ready(function(){
   $("#btn").bind("click",function(){
        $(this).css({ color: "#f00" });
    });
});
</script>
                                  Repaint!
A reflow occurs when a visual change
              requires a change in layout
Initial page load ▪ browser resize ▪ DOM structure change ▪ layout style change
                          layout information retrieved
Reflow
<button id="btn" style="font-size: 30px; padding: 0.5em
    1em">Click Me</button>

<script type="text/javascript">
$(document).ready(function(){
   $("#btn").bind("click",function(){
        $("body").append("<div class="tip">You " +
                         "clicked me!</div>”);
    });
});
</script>                          Reflow!
Repaints and reflows are queued
   up as JavaScript executes
Reflow


var list = $("ul.items");

for (var i=0; i < 10; i++){
    list.append("<li>Item #" + i + "</li>");
}


                             Reflow x 10!
Limiting repaints/reflows
improves overall performance
Solution #1
Perform DOM manipulations
       off-document
Off-Document Operations
• Fast because there's no repaint/reflow
• Techniques:
   – Remove element from the document, make
     changes, insert back into document
   – Set element's display to “none”, make
     changes, set display back to default
   – Build up DOM changes on a
     DocumentFragment then apply all at once
DocumentFragment
• A document-like object
• Not visually represented
• Considered to be owned by the document from
  which it was created
• When passed to appendChild(), appends all
  of its children rather than itself
No
      reflow!


Reflow!
Solution #2
Group Style Changes
Repaint!           Reflow!

$("span.example").css({   color: "red" });
$("span.example").css({   height: "100px" });
                                                Reflow!
$("span.example").css({   fontSize: "25px" });
$("span.example").css({   backgroundColor: "white" });



                                 Repaint!
Grouping Style Changes

.active {
    color: red;
    height: 100px;
    fontSize: 25px;
    background-color: white;
}

$("span.example").addClass("active");


                         Reflow!
Grouping Style Changes



var item = document.getElementById("myItem");
item.style.cssText = "color:red;height:100px;" +
             "font-size:25px;background-color: white");

                         Reflow!
Solution #3
Avoid Accidental Reflow
Accidental Reflow



$("div.example").css({ width: "100px"});

var width = $("div.example").width();


                         Reflow!
What to do?
• Minimize access to layout information
  –   offsetTop, offsetLeft, offsetWidth, offsetHeight
  –   scrollTop, scrollLeft, scrollWidth, scrollHeight
  –   clientTop, clientLeft, clientWidth, clientHeight
  –   Most computed styles
• If a value is used more than once, store in
  local variable
Recap
Things I Know About
                                  JavaScript
                   Professional
                    Wrestling



            YUI




jQuery
The browser UI thread is responsible for
both UI updates and JavaScript execution
           Only one can happen at a time
Responsive UI

UI Thread

 UI Update   JavaScript   UI Update

time
Unresponsive UI

UI Thread

 UI Update       JavaScript    UI Update

time
Unresponsive UI

UI Thread

 UI Update   JavaScript   UI Update

time
Avoid Slow JavaScript
• Don't allow JavaScript to execute for more
  than 50ms
• Break up long JavaScript processes using:
   – Timers
   – Web Workers
Avoid Long UI Updates
• Be careful of repaint and reflow
• Perform complex DOM operations off-
  document
   – Remove elements and re-add them
   – Use DocumentFragment objects
• Group style changes together
• Avoid accidental reflow
Questions?
Etcetera
• My blog:    www.nczonline.net
• My email:   nzakas@yahoo-inc.com
• Twitter:    @slicknet
Creative Commons Images Used
•   http://www.flickr.com/photos/lrargerich/3115367361/
•   http://www.flickr.com/photos/photomonkey/93277011/
•   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/

More Related Content

What's hot

High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)Nicholas Zakas
 
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 Zakas
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011
Nicholas Zakas
 
Nicholas' Performance Talk at Google
Nicholas' Performance Talk at GoogleNicholas' Performance Talk at Google
Nicholas' Performance Talk at Google
Nicholas Zakas
 
jQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksjQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & Tricks
Addy Osmani
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web App
Edureka!
 
High Performance Snippets
High Performance SnippetsHigh Performance Snippets
High Performance Snippets
Steve Souders
 
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
Matt Raible
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
Yevgeniy Brikman
 
Learning from the Best jQuery Plugins
Learning from the Best jQuery PluginsLearning from the Best jQuery Plugins
Learning from the Best jQuery Plugins
Marc Grabanski
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
Yevgeniy Brikman
 
The DOM is a Mess @ Yahoo
The DOM is a Mess @ YahooThe DOM is a Mess @ Yahoo
The DOM is a Mess @ Yahoo
jeresig
 
HTML5 vs Silverlight
HTML5 vs SilverlightHTML5 vs Silverlight
HTML5 vs SilverlightMatt Casto
 
How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?
How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?
How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?
Katy Slemon
 
Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)
Nicholas Zakas
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
All Things Open
 
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJSDeveloping Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Shekhar Gulati
 
Cache is King
Cache is KingCache is King
Cache is King
Steve Souders
 
Ajax Security
Ajax SecurityAjax Security
Ajax Security
Joe Walker
 
Instant and offline apps with Service Worker
Instant and offline apps with Service WorkerInstant and offline apps with Service Worker
Instant and offline apps with Service Worker
Chang W. Doh
 

What's hot (20)

High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 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)
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011
 
Nicholas' Performance Talk at Google
Nicholas' Performance Talk at GoogleNicholas' Performance Talk at Google
Nicholas' Performance Talk at Google
 
jQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksjQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & Tricks
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web App
 
High Performance Snippets
High Performance SnippetsHigh Performance Snippets
High Performance Snippets
 
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
 
Learning from the Best jQuery Plugins
Learning from the Best jQuery PluginsLearning from the Best jQuery Plugins
Learning from the Best jQuery Plugins
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
 
The DOM is a Mess @ Yahoo
The DOM is a Mess @ YahooThe DOM is a Mess @ Yahoo
The DOM is a Mess @ Yahoo
 
HTML5 vs Silverlight
HTML5 vs SilverlightHTML5 vs Silverlight
HTML5 vs Silverlight
 
How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?
How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?
How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?
 
Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJSDeveloping Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJS
 
Cache is King
Cache is KingCache is King
Cache is King
 
Ajax Security
Ajax SecurityAjax Security
Ajax Security
 
Instant and offline apps with Service Worker
Instant and offline apps with Service WorkerInstant and offline apps with Service Worker
Instant and offline apps with Service Worker
 

Viewers also liked

JavaScript Prototype and Module Pattern
JavaScript Prototype and Module PatternJavaScript Prototype and Module Pattern
JavaScript Prototype and Module Pattern
Narendra Sisodiya
 
JavaScript Conditional Statements
JavaScript Conditional StatementsJavaScript Conditional Statements
JavaScript Conditional Statements
Marlon Jamera
 
Evolutionary Algorithms
Evolutionary AlgorithmsEvolutionary Algorithms
Evolutionary Algorithms
Reem Alattas
 
She Looks Just Like Me 2017
She Looks Just Like Me 2017She Looks Just Like Me 2017
She Looks Just Like Me 2017
Reem Alattas
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
Reem Alattas
 
Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]
Aaron Gustafson
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 

Viewers also liked (7)

JavaScript Prototype and Module Pattern
JavaScript Prototype and Module PatternJavaScript Prototype and Module Pattern
JavaScript Prototype and Module Pattern
 
JavaScript Conditional Statements
JavaScript Conditional StatementsJavaScript Conditional Statements
JavaScript Conditional Statements
 
Evolutionary Algorithms
Evolutionary AlgorithmsEvolutionary Algorithms
Evolutionary Algorithms
 
She Looks Just Like Me 2017
She Looks Just Like Me 2017She Looks Just Like Me 2017
She Looks Just Like Me 2017
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
 
Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 

Similar to High Performance JavaScript - jQuery Conference SF Bay Area 2010

CyberArk Impact 2017 - REST for the Rest of Us
CyberArk Impact 2017 - REST for the Rest of UsCyberArk Impact 2017 - REST for the Rest of Us
CyberArk Impact 2017 - REST for the Rest of Us
Joe Garcia
 
Continuous Delivery - Voxxed Days Cluj-Napoca 2017
Continuous Delivery - Voxxed Days Cluj-Napoca 2017Continuous Delivery - Voxxed Days Cluj-Napoca 2017
Continuous Delivery - Voxxed Days Cluj-Napoca 2017
Rafał Leszko
 
Medium TechTalk — iOS
Medium TechTalk — iOSMedium TechTalk — iOS
Medium TechTalk — iOS
jimmyatmedium
 
Angular - Improve Runtime performance 2019
Angular - Improve Runtime performance 2019Angular - Improve Runtime performance 2019
Angular - Improve Runtime performance 2019
Eliran Eliassy
 
[143]Inside fuse deview 2016
[143]Inside fuse   deview 2016[143]Inside fuse   deview 2016
[143]Inside fuse deview 2016
NAVER D2
 
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
Timothy Fisher
 
Jenkins CI for MacDevOps
Jenkins CI for MacDevOpsJenkins CI for MacDevOps
Jenkins CI for MacDevOps
Timothy Sutton
 
Introducing PanelKit
Introducing PanelKitIntroducing PanelKit
Introducing PanelKit
Louis D'hauwe
 
Plug yourself in and your app will never be the same (1 hr edition)
Plug yourself in and your app will never be the same (1 hr edition)Plug yourself in and your app will never be the same (1 hr edition)
Plug yourself in and your app will never be the same (1 hr edition)
Mikkel Flindt Heisterberg
 
[1C1]Service Workers
[1C1]Service Workers[1C1]Service Workers
[1C1]Service Workers
NAVER D2
 
jQuery UI and Plugins
jQuery UI and PluginsjQuery UI and Plugins
jQuery UI and Plugins
Marc Grabanski
 
The fundamental problems of GUI applications and why people choose React
The fundamental problems of GUI applications and why people choose ReactThe fundamental problems of GUI applications and why people choose React
The fundamental problems of GUI applications and why people choose React
Oliver N
 
JavaFX GUI architecture with Clojure core.async
JavaFX GUI architecture with Clojure core.asyncJavaFX GUI architecture with Clojure core.async
JavaFX GUI architecture with Clojure core.async
Falko Riemenschneider
 
BPM-4 Migration from jBPM to Activiti
BPM-4 Migration from jBPM to ActivitiBPM-4 Migration from jBPM to Activiti
BPM-4 Migration from jBPM to Activiti
Alfresco Software
 
Red Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Red Hat JBoss BRMS and BPMS Workbench and Rich Client TechnologyRed Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Red Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Mark Proctor
 
System insight without Interference
System insight without InterferenceSystem insight without Interference
System insight without Interference
Tony Tam
 
Implementing auto complete using JQuery
Implementing auto complete using JQueryImplementing auto complete using JQuery
Implementing auto complete using JQuery
Bhushan Mulmule
 
Protractor Tutorial Quality in Agile 2015
Protractor Tutorial Quality in Agile 2015Protractor Tutorial Quality in Agile 2015
Protractor Tutorial Quality in Agile 2015
Andrew Eisenberg
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
Kaloyan Kosev
 

Similar to High Performance JavaScript - jQuery Conference SF Bay Area 2010 (20)

CyberArk Impact 2017 - REST for the Rest of Us
CyberArk Impact 2017 - REST for the Rest of UsCyberArk Impact 2017 - REST for the Rest of Us
CyberArk Impact 2017 - REST for the Rest of Us
 
TechGarage Hackaton
TechGarage HackatonTechGarage Hackaton
TechGarage Hackaton
 
Continuous Delivery - Voxxed Days Cluj-Napoca 2017
Continuous Delivery - Voxxed Days Cluj-Napoca 2017Continuous Delivery - Voxxed Days Cluj-Napoca 2017
Continuous Delivery - Voxxed Days Cluj-Napoca 2017
 
Medium TechTalk — iOS
Medium TechTalk — iOSMedium TechTalk — iOS
Medium TechTalk — iOS
 
Angular - Improve Runtime performance 2019
Angular - Improve Runtime performance 2019Angular - Improve Runtime performance 2019
Angular - Improve Runtime performance 2019
 
[143]Inside fuse deview 2016
[143]Inside fuse   deview 2016[143]Inside fuse   deview 2016
[143]Inside fuse deview 2016
 
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
 
Jenkins CI for MacDevOps
Jenkins CI for MacDevOpsJenkins CI for MacDevOps
Jenkins CI for MacDevOps
 
Introducing PanelKit
Introducing PanelKitIntroducing PanelKit
Introducing PanelKit
 
Plug yourself in and your app will never be the same (1 hr edition)
Plug yourself in and your app will never be the same (1 hr edition)Plug yourself in and your app will never be the same (1 hr edition)
Plug yourself in and your app will never be the same (1 hr edition)
 
[1C1]Service Workers
[1C1]Service Workers[1C1]Service Workers
[1C1]Service Workers
 
jQuery UI and Plugins
jQuery UI and PluginsjQuery UI and Plugins
jQuery UI and Plugins
 
The fundamental problems of GUI applications and why people choose React
The fundamental problems of GUI applications and why people choose ReactThe fundamental problems of GUI applications and why people choose React
The fundamental problems of GUI applications and why people choose React
 
JavaFX GUI architecture with Clojure core.async
JavaFX GUI architecture with Clojure core.asyncJavaFX GUI architecture with Clojure core.async
JavaFX GUI architecture with Clojure core.async
 
BPM-4 Migration from jBPM to Activiti
BPM-4 Migration from jBPM to ActivitiBPM-4 Migration from jBPM to Activiti
BPM-4 Migration from jBPM to Activiti
 
Red Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Red Hat JBoss BRMS and BPMS Workbench and Rich Client TechnologyRed Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Red Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
 
System insight without Interference
System insight without InterferenceSystem insight without Interference
System insight without Interference
 
Implementing auto complete using JQuery
Implementing auto complete using JQueryImplementing auto complete using JQuery
Implementing auto complete using JQuery
 
Protractor Tutorial Quality in Agile 2015
Protractor Tutorial Quality in Agile 2015Protractor Tutorial Quality in Agile 2015
Protractor Tutorial Quality in Agile 2015
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
 

More from Nicholas Zakas

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 MenaceNicholas Zakas
 
The Pointerless Web
The Pointerless WebThe Pointerless Web
The Pointerless Web
Nicholas Zakas
 
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
 
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
Nicholas Zakas
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
Nicholas Zakas
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
Nicholas Zakas
 
Mobile Web Speed Bumps
Mobile Web Speed BumpsMobile Web Speed Bumps
Mobile Web Speed Bumps
Nicholas Zakas
 
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)
Nicholas Zakas
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
Nicholas Zakas
 
Extreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI CompressorExtreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI Compressor
Nicholas Zakas
 
Writing Efficient JavaScript
Writing Efficient JavaScriptWriting Efficient JavaScript
Writing Efficient JavaScript
Nicholas Zakas
 
Speed Up Your JavaScript
Speed Up Your JavaScriptSpeed Up Your JavaScript
Speed Up Your JavaScript
Nicholas Zakas
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScript
Nicholas Zakas
 
JavaScript Variable Performance
JavaScript Variable PerformanceJavaScript Variable Performance
JavaScript Variable Performance
Nicholas Zakas
 
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
Nicholas Zakas
 
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)
Nicholas Zakas
 
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)
Nicholas Zakas
 

More from Nicholas Zakas (17)

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
 
The Pointerless Web
The Pointerless WebThe Pointerless Web
The Pointerless Web
 
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)
 
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
 
Mobile Web Speed Bumps
Mobile Web Speed BumpsMobile Web Speed Bumps
Mobile Web Speed Bumps
 
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)
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
 
Extreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI CompressorExtreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI Compressor
 
Writing Efficient JavaScript
Writing Efficient JavaScriptWriting Efficient JavaScript
Writing Efficient JavaScript
 
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)
 
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)
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 

High Performance JavaScript - jQuery Conference SF Bay Area 2010

  • 1. High Performance JavaScript Nicholas C. Zakas Principal Front End Engineer, Yahoo! jQuery Conference – SF Bay Area, April 24 2010
  • 2.
  • 6.
  • 7. Things I Know About JavaScript Professional Wrestling YUI jQuery
  • 8.
  • 9.
  • 10.
  • 12. Old computers ran slow applications Small amounts of CPU power and memory
  • 13. New computers are generally faster but slow applications still exist More CPU + more memory = less disciplined application development
  • 14. It's still possible to write slow JavaScript on the new, faster JavaScript engines
  • 15. How can I improve JavaScript performance?
  • 16. How can I improve JavaScript performance? How can I make this fast???
  • 17. How can I improve JavaScript performance? How can I make this fast??? Why is this so slow?????
  • 18.
  • 19. Many aspects conspire to make JavaScript slow Awareness is the first step to solution
  • 20. The UI Thread The brains of the operation
  • 21. The browser UI thread is responsible for both UI updates and JavaScript execution Only one can happen at a time
  • 22. Jobs for UI updates and JavaScript execution are added to a UI queue if the UI thread is busy Each job must wait in line for its turn to execute
  • 23. <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button> <script type="text/javascript"> $(document).ready(function(){ $("#btn").bind("click",function(){ //do something }); }); </script>
  • 25. When Clicked UI Thread time UI Queue UI Update onclick UI Update
  • 26. When Clicked UI Thread UI Update time UI Queue onclick Draw down state UI Update
  • 27. When Clicked UI Thread UI Update onclick time UI Queue UI Update
  • 28. When Clicked UI Thread UI Update onclick UI Update time UI Queue Draw up state
  • 29. No UI updates while JavaScript is executing!
  • 30. JavaScript May Cause UI Update <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button> <script type="text/javascript"> $(document).ready(function(){ $("#btn").bind("click",function(){ $("body").append("<div class="tip">You " + "clicked me!</div>”); }); }); </script>
  • 31. A UI update must use the latest info available
  • 32. Long-running JavaScript = Unresponsive UI
  • 33. Responsive UI UI Thread UI Update JavaScript UI Update time
  • 34. Unresponsive UI UI Thread UI Update JavaScript UI Update time
  • 35. The runaway script timer prevents JavaScript from running for too long Each browser imposes its own limit (except Opera)
  • 40. 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
  • 41. 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
  • 42. Translation: No single JavaScript job should execute for more than 100ms to ensure a responsive UI
  • 44. function processArray(items, process, callback){ for (var i=0,len=items.length; i < len; i++){ process(items[i]); } callback(); }
  • 45. Timers to the rescue!
  • 46. JavaScript Timers • Created using setTimeout() • Schedules a new JavaScript execution job for some time in the future • When the delay is up, the job is added to the UI queue – Note: This does not guarantee execution after the delay, just that the job is added to the UI queue and will be executed when appropriate
  • 47. JavaScript Timers • For complex processing, split up into timed functionality • Use timers to delay some processing for later
  • 48. 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); }
  • 49. When Clicked UI Thread time UI Queue UI Update onclick UI Update
  • 50. When Clicked UI Thread UI Update time UI Queue onclick UI Update
  • 51. When Clicked UI Thread UI Update onclick time UI Queue UI Update
  • 52. When Clicked UI Thread UI Update onclick UI Update time UI Queue
  • 53. After 25ms UI Thread UI Update onclick UI Update time UI Queue JavaScript
  • 54. After 25ms UI Thread UI Update onclick UI Update JavaScript time UI Queue
  • 55. After Another 25ms UI Thread UI Update onclick UI Update JavaScript time UI Queue JavaScript
  • 56. After Another 25ms UI Thread UI Update onclick UI Update JavaScript JavaScript time UI Queue
  • 57. Web Workers to the rescue!
  • 58.
  • 59. Web Workers • Asynchronous JavaScript execution • Execution happens in a separate process – Not on the UI thread = no UI delays • Data-driven API – Data is serialized when sending data into or out of Worker – No access to DOM, BOM – Completely separate execution environment
  • 60. //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); };
  • 61. When Clicked UI Thread time UI Queue UI Update onclick UI Update
  • 62. When Clicked UI Thread UI Update time UI Queue onclick UI Update
  • 63. When Clicked UI Thread UI Update onclick time UI Queue UI Update
  • 64. When Clicked UI Thread UI Update onclick time Worker Thread UI Queue UI Update
  • 65. When Clicked UI Thread UI Update onclick UI Update time Worker Thread UI Queue JavaScript
  • 66. Worker Thread Complete UI Thread UI Update onclick UI Update time UI Queue onmessage
  • 67. Worker Thread Complete UI Thread UI Update onclick UI Update onmessage time UI Queue
  • 69. Repaint and Reflow UI update jobs
  • 70. Long UI updates = Unresponsive UI
  • 71. Unresponsive UI UI Thread UI Update JavaScript UI Update time
  • 72. Long UI updates = Unresponsive UI = Frustrated users
  • 73. JavaScript can cause long UI updates
  • 74. A repaint occurs when a visual change doesn't require recalculation of layout Changes to visibility, colors (text/background), background images, etc.
  • 75. Repaint <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button> <script type="text/javascript"> $(document).ready(function(){ $("#btn").bind("click",function(){ $(this).css({ color: "#f00" }); }); }); </script> Repaint!
  • 76. A reflow occurs when a visual change requires a change in layout Initial page load ▪ browser resize ▪ DOM structure change ▪ layout style change layout information retrieved
  • 77. Reflow <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button> <script type="text/javascript"> $(document).ready(function(){ $("#btn").bind("click",function(){ $("body").append("<div class="tip">You " + "clicked me!</div>”); }); }); </script> Reflow!
  • 78. Repaints and reflows are queued up as JavaScript executes
  • 79. Reflow var list = $("ul.items"); for (var i=0; i < 10; i++){ list.append("<li>Item #" + i + "</li>"); } Reflow x 10!
  • 81. Solution #1 Perform DOM manipulations off-document
  • 82. Off-Document Operations • Fast because there's no repaint/reflow • Techniques: – Remove element from the document, make changes, insert back into document – Set element's display to “none”, make changes, set display back to default – Build up DOM changes on a DocumentFragment then apply all at once
  • 83. DocumentFragment • A document-like object • Not visually represented • Considered to be owned by the document from which it was created • When passed to appendChild(), appends all of its children rather than itself
  • 84. No reflow! Reflow!
  • 86. Repaint! Reflow! $("span.example").css({ color: "red" }); $("span.example").css({ height: "100px" }); Reflow! $("span.example").css({ fontSize: "25px" }); $("span.example").css({ backgroundColor: "white" }); Repaint!
  • 87. Grouping Style Changes .active { color: red; height: 100px; fontSize: 25px; background-color: white; } $("span.example").addClass("active"); Reflow!
  • 88. Grouping Style Changes var item = document.getElementById("myItem"); item.style.cssText = "color:red;height:100px;" + "font-size:25px;background-color: white"); Reflow!
  • 90. Accidental Reflow $("div.example").css({ width: "100px"}); var width = $("div.example").width(); Reflow!
  • 91. What to do? • Minimize access to layout information – offsetTop, offsetLeft, offsetWidth, offsetHeight – scrollTop, scrollLeft, scrollWidth, scrollHeight – clientTop, clientLeft, clientWidth, clientHeight – Most computed styles • If a value is used more than once, store in local variable
  • 92. Recap
  • 93.
  • 94. Things I Know About JavaScript Professional Wrestling YUI jQuery
  • 95. The browser UI thread is responsible for both UI updates and JavaScript execution Only one can happen at a time
  • 96. Responsive UI UI Thread UI Update JavaScript UI Update time
  • 97. Unresponsive UI UI Thread UI Update JavaScript UI Update time
  • 98. Unresponsive UI UI Thread UI Update JavaScript UI Update time
  • 99. Avoid Slow JavaScript • Don't allow JavaScript to execute for more than 50ms • Break up long JavaScript processes using: – Timers – Web Workers
  • 100. Avoid Long UI Updates • Be careful of repaint and reflow • Perform complex DOM operations off- document – Remove elements and re-add them – Use DocumentFragment objects • Group style changes together • Avoid accidental reflow
  • 102. Etcetera • My blog: www.nczonline.net • My email: nzakas@yahoo-inc.com • Twitter: @slicknet
  • 103. Creative Commons Images Used • http://www.flickr.com/photos/lrargerich/3115367361/ • http://www.flickr.com/photos/photomonkey/93277011/ • 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/

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