High Performance JavaScript<br />Nicholas C. Zakas| CapitolJS | September 18, 2011<br />
Who's this guy?<br />Co-Creator csslint.net<br />Contributor,<br />Creator of YUI Test<br />Ex-tech lead<br />Yahoo!<br />...
@slicknet<br />(complaints: @voodootikigod)<br />
Does JavaScript performance matter?<br />
All browsers now haveoptimizing JavaScript engines<br />Tracemonkey/<br />JaegarMonkey<br />(3.5+)<br />V8<br />(all)<br /...
http://ie.microsoft.com/testdrive/benchmarks/sunspider/default.html<br />
Old computers ran slow applications<br />Small amounts of CPU power and memory<br />
New computers are generally faster but<br />slow applications still exist<br />More CPU + more memory = less disciplined a...
Oh yeah, one more thing<br />
It's still possible to write slow JavaScript<br />
JavaScript performancedirectlyaffects user experience<br />
The UI Threadaka Browser Event Loop<br />
The browser UI thread is responsible for<br />both UI updates and JavaScript execution<br />Only one can happen at a time<...
Jobs for UI updates and JavaScript execution<br />are added to a UI queue<br />Each job must wait in line for its turn to ...
<button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button><br /><script type="text/javascript"><br />w...
Before Click<br />UI Thread<br />time<br />UI Queue<br />
When Clicked<br />UI Thread<br />time<br />UI Queue<br />UI Update<br />onclick<br />UI Update<br />
When Clicked<br />UI Thread<br />UI Update<br />time<br />UI Queue<br />onclick<br />Draw down state<br />UI Update<br />
When Clicked<br />UI Thread<br />onclick<br />UI Update<br />time<br />UI Queue<br />UI Update<br />
When Clicked<br />UI Thread<br />onclick<br />UI Update<br />UI Update<br />time<br />UI Queue<br />Draw up state<br />
No UI updates while JavaScript is executing<br />
JavaScript May Cause UI Update<br /><button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button><br /><s...
A UI update must use the latest info available<br />
Long-running JavaScript=Unresponsive UI<br />
Responsive UI<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />time<br />
Unresponsive UI<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />time<br />
The longer JavaScript runs,the worse the user experience<br />
The runaway script timer prevents JavaScript<br />from running for too long<br />Each browser imposes its own limit (excep...
Internet Explorer<br />
Firefox<br />
Safari<br />
Chrome<br />
Runaway Script Timer Limits<br />Internet Explorer: 5 million statements<br />Firefox: 10 seconds<br />Safari: 5 seconds<b...
How Long Is Too Long?<br />“0.1 second [100ms] is about the limit for having the user feel that the system is reacting ins...
Translation:No single JavaScript job should execute for more than 100ms to ensure a responsive UI<br />
Recommendation:Limit JavaScript execution to no more than 50msmeasured on IE6 :)<br />
Loadtime TechniquesDon't let JavaScript interfere with page load performance<br />
During page load, JavaScript takes more time on the UI thread<br />
<!doctype html><br /><html><br /><head><br />    <title>Example</title><br /></head><br /><body><br />    <p>Hello world!<...
Result<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />time<br />
Result<br />UI Thread<br />foo.js<br />See ya!<br />Hello world!<br />time<br />
Result<br />UI Thread<br />Download<br />See ya!<br />Hello world!<br />Parse<br />Run<br />time<br />The UI thread needs ...
Result<br />UI Thread<br />Download<br />See ya!<br />Hello world!<br />Parse<br />Run<br />Variable<br />Constant<br />Do...
Translation:The page doesn't render while JavaScript is downloading, parsing, or executing during page load<br />
<!doctype html><br /><html><br /><head><br />    <title>Example</title><br /></head><br /><body><br /><script src="foo.js"...
Result<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />JavaScript<br />JavaScript<br />time<br />The mor...
Technique #1: Load scripts dynamically<br />
Basic Technique<br />var script = document.createElement("script"),<br />    body;<br />script.type = "text/javascript";<b...
Downloads no longer block the UI thread<br />
<!doctype html><br /><html><br /><head><br />    <title>Example</title><br /></head><br /><body><br />    <p>Hello world!<...
Using HTML <script><br />UI Thread<br />Download<br />See ya!<br />Hello world!<br />Parse<br />Run<br />time<br />
<!doctype html><br /><html><br /><head><br />    <title>Example</title><br /></head><br /><body><br />    <p>Hello world!<...
Using Dynamic Scripts<br />UI Thread<br />See ya!<br />Hello world!<br />UI Update<br />Run<br />time<br />Download<br />P...
function loadScript(url, callback){var script = document.createElement("script"),    body = document.body;script.type = "t...
Usage<br />loadScript("foo.js", function(){<br />    alert("Loaded!");<br />});<br />
Timing Note:Script execution begins immediately after download and parse – timing of execution is not guaranteed<br />
Technique #2: Defer scripts<br />
<!doctype html><br /><html><br /><head><br />    <title>Example</title><br /></head><br /><body><br />    <p>Hello world!<...
Support for <script defer><br />?<br />5.0<br />3.5<br />7.0<br />4.0<br />
Deferred scripts begin to download immediately, but don't execute until all UI updates complete<br />
Using <script defer><br />UI Thread<br />See ya!<br />Hello world!<br />More UI<br />Run<br />More UI<br />time<br />Downl...
Timing Note:Although scripts always execute after UI updates complete, the order of multiple <script defer> scripts is not...
Technique #3: Asynchronous scripts<br />
<!doctype html><br /><html><br /><head><br />    <title>Example</title><br /></head><br /><body><br />    <p>Hello world!<...
Support for <script async><br />?<br />5.0<br />3.6<br />7.0<br />10<br />
Asynchronous scripts behave a lot like dynamic scripts<br />
Using <script async><br />UI Thread<br />See ya!<br />Hello world!<br />UI Update<br />Run<br />time<br />Download<br />Pa...
Note:Order of execution is explicitly not preserved for asynchronous scripts<br />
Runtime TechniquesWays to ensure JavaScript doesn't run away<br />
function processArray(items, process, callback){<br />for (var i=0,len=items.length; i < len; i++){<br />        process(i...
Technique #1: Timers<br />
//create a new timer and delay by 500ms<br />setTimeout(function(){<br />//code to execute here<br />}, 500);<br />setTime...
function timedProcessArray(items, process, callback){<br />//create a clone of the original  var todo = items.concat();<br...
When Clicked<br />UI Thread<br />time<br />UI Queue<br />UI Update<br />onclick<br />UI Update<br />
When Clicked<br />UI Thread<br />UI Update<br />time<br />UI Queue<br />onclick<br />UI Update<br />
When Clicked<br />UI Thread<br />onclick<br />UI Update<br />time<br />UI Queue<br />UI Update<br />
When Clicked<br />UI Thread<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />
After 25ms<br />UI Thread<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />JavaScript<br />
After 25ms<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />
After Another 25ms<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />...
After Another 25ms<br />UI Thread<br />JavaScript<br />JavaScript<br />UI Update<br />UI Update<br />onclick<br />time<br ...
Technique #2: Script Yielding<br />NEW!<br />
//delay a function until after UI updates are done<br />setImmediate(function(){<br />//code to execute here<br />});<br /...
Support for Script Yielding<br />?<br />?<br />?<br />?<br />10<br />msSetIntermediate()<br />
functionyieldingProcessArray(items, process, callback){<br />//create a clone of the originalvartodo = items.concat();<br ...
When Clicked<br />UI Thread<br />time<br />UI Queue<br />UI Update<br />onclick<br />UI Update<br />
When Clicked<br />UI Thread<br />UI Update<br />time<br />UI Queue<br />onclick<br />UI Update<br />
When Clicked<br />UI Thread<br />onclick<br />UI Update<br />time<br />UI Queue<br />UI Update<br />
When Clicked<br />UI Thread<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />
After Last UI Update<br />UI Thread<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />JavaScript<br />
After Last UI Update<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />
No Other UI Updates<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br /...
No Other UI Updates<br />UI Thread<br />JavaScript<br />JavaScript<br />UI Update<br />UI Update<br />onclick<br />time<br...
Technique #3: Web Workers<br />
Support for Web Workers<br />10.6<br />4.0<br />3.5<br />4.0<br />10<br />
Web Workers<br />Asynchronous JavaScript execution<br />Execution happens outside the UI thread<br />Doesn’t block UI upda...
//in page<br />var worker = new Worker("process.js");<br />worker.onmessage = function(event){<br />    useData(event.data...
When Clicked<br />UI Thread<br />time<br />UI Queue<br />UI Update<br />onclick<br />UI Update<br />
When Clicked<br />UI Thread<br />UI Update<br />time<br />UI Queue<br />onclick<br />UI Update<br />
When Clicked<br />UI Thread<br />onclick<br />UI Update<br />time<br />UI Queue<br />UI Update<br />
When Clicked<br />UI Thread<br />onclick<br />UI Update<br />time<br />UI Queue<br />Worker Thread<br />UI Update<br />
When Clicked<br />UI Thread<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />Worker Thread<br />Jav...
Worker Thread Complete<br />UI Thread<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />onmessage<br />
Worker Thread Complete<br />UI Thread<br />onmessage<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />
Recap<br />
The browser UI thread is responsible for<br />both UI updates and JavaScript execution<br />Only one can happen at a time<...
Responsive UI<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />time<br />
Unresponsive UI<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />time<br />
Avoid Slow Loading JavaScript<br />Dynamically created scripts<br />Deferred scripts<br />Asynchronous scripts<br />
Avoid Slow JavaScript<br />Don't allow JavaScript to execute for more than 50ms<br />Break up long JavaScript processes us...
Etcetera<br />My blog: 	www.nczonline.net<br />Twitter:		@slicknet<br />These Slides:	slideshare.net/nzakas<br />Hire us:	...
Questions?<br />
Creative Commons Images Used<br />http://www.flickr.com/photos/lrargerich/3115367361/<br />http://www.flickr.com/photos/hi...
Upcoming SlideShare
Loading in...5
×

High Performance JavaScript (CapitolJS 2011)

14,788

Published on

Published in: Technology, Education
7 Comments
66 Likes
Statistics
Notes
  • Hi Nicholas!, I just want to let you know that your books are really awesome and helpful. Just wanna ask when are you going to publish a new one? I really love your books BTW and thank you for writing them up!.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Thank you, very useful.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • @HYCLEN No Spam!
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • 11-Bom dia amigos, Venham conhecer nossos Servidores de Mu Online
    O Jogando.net/mu Mu Online Season 6
    Fazemos sua Diversão com qualidade,há mais de 5 anos
    Servers ON 24 horas por dia.
    Vários Server esperando por você.Venha se divertir de verdade.
    Venham participar do 6° Megaultrasuperhiper Evento Castle Siege
    Sejam benvindos ao nosso Servidor.
    >>Kits DIAMOND,Com asas LVL 4,os kits mais fortes e raros do servidor ,venham conferir.
    >>Qual o seu Time ?? Tenha o seu Time do coração no Mu Online.Sets do seu Time preferido
    >>Confiram a nova versão do Shild mais usado no servidor o SHILD POWER v3.
    >> Lançamento do NOVO Kit Fusion V2,Kit hiper top e bonito.
    Você só encontra no http://www.jogando.net/mu/
    Facebook: http://www.facebook.com/profile.php?id=100002113910611
    Site http://www.jogando.net/mu/ HYCLEN Divulgadora Oficial !!!
    Boa Semana á todos !!!
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Yes, High Performance Javascript
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
14,788
On Slideshare
0
From Embeds
0
Number of Embeds
8
Actions
Shares
0
Downloads
373
Comments
7
Likes
66
Embeds 0
No embeds

No notes for slide
  • 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.
  • 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
  • High Performance JavaScript (CapitolJS 2011)

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

      Clipping is a handy way to collect important slides you want to go back to later.

    ×