7. After all, all browsers now have
optimizing JavaScript engines
Tracemonkey/ V8 Squirrelfish Chakra Karakan
JaegarMonkey (all) (4+) (9+) (10.5+)
(3.5+)
47. 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
48. Translation:
No single JavaScript job should
execute for more than 100ms to
ensure a responsive UI
56. Result
UI Thread
Hello world! Download Parse Run See ya!
time
The UI thread needs to wait for the script to
download, parse, and run before continuing
57. Result
UI Thread
Hello world! Download Parse Run See ya!
Variable Constant
Download time takes the longest and is variable
58. Translation:
The page doesn't render while
JavaScript is downloading, parsing, or
executing during page load
60. Result
UI Thread
JavaScript UI Update JavaScript UI Update JavaScript
time
The more scripts to download in between UI
updates, the longer the page takes to render
64. Put Scripts at Bottom
UI Thread
UI Update UI Update JavaScript JavaScript JavaScript
time
Even if there are multiple scripts, the page
renders quickly
76. Using Dynamic Scripts
UI Thread
Hello world! See ya! Run UI Update
time
Download Parse
Only code execution happens on the UI thread,
which means less blocking of UI updates
79. Timing Note:
Script execution begins immediately
after download and parse – timing of
execution is not guaranteed
80. Using Dynamic Scripts
UI Thread
Hello world! Run See ya! UI Update
time
Download Parse
Depending on time to download and script size,
execution may happen before next UI update
84. Deferred scripts begin to
download immediately,
but don't execute until all UI
updates complete
85. Using <script defer>
UI Thread
Hello world! See ya! More UI More UI Run
time
Download Parse
Similar to dynamic script nodes, but with a
guarantee that execution will happen last
86. Timing Note:
Although scripts always execute after
UI updates complete, the order of
multiple <script defer> scripts is not
guaranteed across browsers
91. Using <script async>
UI Thread
Hello world! See ya! Run UI Update
time
Download Parse
Download begins immediately and execution is
slotted in at first available spot
96. //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
97. 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);
}
108. Web Workers
â—Ź
Asynchronous JavaScript execution
â—Ź
Execution happens outside of UI thread
â—Ź
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
109. //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);
};
122. A repaint occurs when a visual change doesn't
require recalculation of layout
Changes to visibility, colors (text/background), background images, etc.
124. 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
126. Repaints and reflows are queued
up as JavaScript executes
and then executed in order
127. Reflow
var list = document.getElementsByClassName("items")[0],
i, item;
for (i=0; i < 10; i++){
item = document.createElement("li");
item.innerHTML = "Item #" + i;
list.appendChild(item);
}
Reflow x 10!
130. 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
131. 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
132. DocumentFragment
var list = document.getElementsByClassName("items")[0],
fragment = document.createDocumentFragment(),
i, item;
for (i=0; i < 10; i++){
item = document.createElement("li");
item.innerHTML = "Item #" + i;
fragment.appendChild(item);
}
list.appendChild(fragment);
1 Reflow
139. 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
148. Avoid Slow Loading JavaScript
• Put scripts at the bottom
• Concatenate scripts into as few files as
possible
• Choose the right way to load your scripts
– Dynamically created scripts
– Deferred scripts
– Asynchronous scripts
149. Avoid Slow JavaScript
• Don't allow JavaScript to execute for more
than 50ms
• Break up long JavaScript processes using:
– Timers
– Web Workers
150. 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