Transcript Slide 1

WEB WORKERS
Amitesh Madhur ([email protected])
(Exceptional Performance, Bangalore)
1
Why Web Workers?
JavaScript should not execute for longer than 100
milliseconds to ensure responsive UI. My recommendation,
though, is to keep JavaScript under 50 milliseconds at a
time, because why even try to get close to that?
- Nicholas Zakas
2
What is Web Worker?
self.postMessage(obj || str)
3
AGENDA
•
•
•
•
•
•
•
•
•
•
Without Web Workers
With Web Workers
What are Web Workers
Worker Environment
Subworkers/Delegation
Inline Worker
Restrictions
Browser Support
Use cases
Demo
4
Without Web Workers
Chrome
Internet Explorer
Firefox
5
With Web Workers
Chrome
Internet Explorer
Firefox
6
What are Web Workers?
• Scripts running in background.
• Heavy Weight Scripts.
7
What are Web Workers?
myworker.js
// create web worker
worker.postMessage({‘cmd’:gen_num});
self.onmessage = fn(e){}
// task completed
self.postMessage(arrayOfRandomNum);
worker.terminate();
worker.onmessage = fn(e){
// update DOM with e.data
}
8
Difference from other approach.
• How different from setTimeout?
• How different from AJAX?
9
So what does Worker look like?
Main Page
1
// Check if workers are supported.
if (typeof(Worker) == "undefined") {
document.getElementById(‘support’).textContent = ‘Your browser does
not support Web Workers’;
return false;
}
2
// worker object
var worker = new Worker('worker.js');
3
// post message to worker
worker.postMessage(‘Are you there?’);
4
5
// error handling
worker.onerror = function(event){
console.log(event.message + ‘ in file = ’ + event.filename + ‘ at line #’
+ event.lineno );
};
// on message handler
worker.onmessage = function (event) {
document.getElementById('result').textContent = event.data;
}
10
So what does Worker look like?
worker.js
1 self.onmessage = function(event){
postMessage(event.data + ‘ Worker says: Yes I am here.’);
}
OR
2 self.addEventListener('message', function(e) {
self.postMessage(event.data +‘ Worker says: Yes I am here.’);
}, false);
11
Worker Environment
• No BOM
• No DOM
• !parent
setTimeout, setInterval
navigator object
location object (read-only)
XMLHttpRequest
Spawning other web workers
12
Subworker/Delegation
• Ability to spawn child workers
– Breaks up huge task into smaller chunks
• Sub workers should be in hosted in the same
domain
• Location of sub worker file is relative to parent
worker (and not main page).
13
Subworker/Delegation
Parent Worker
self.onmessage = function(event){
var num_workers = 4; // total sub workers
var pending_workers = num_workers;
// loop though the sub-workers
for (var i = 0; i < num_workers; i++) {
1 var worker = new Worker('subworker.js');
2 worker.postMessage(event.data);
// on message
3 worker.onmessage = function(event) {
var str += event.data; // collect data
pending_workers -= 1; // workers pending
// case: all response collected then post to main page
4
if (pending_workers == 0) self.postMessage(str);
} // on message sub-worker end
} // loop end
}
14
Subworker/Delegation
subworker.js
onmessage = function(event){
postMessage(event.data + ‘ Sub Worker says: Yes I am here.’);
}
15
Inline worker
• Worker script on the fly
– Without creating separate worker file
• BlobBuilder interface
16
Inline worker
• Worker script on the fly
– Without creating separate worker file
• BlobBuilder interface
var bb = new BlobBuilder();
bb.append("onmessage = function(e) { postMessage('msg
from worker'); }");
var blobURL = window.URL.createObjectURL(bb.getBlob());
var worker = new Worker(blobURL);
worker.postMessage('Hello'); // post message to start worker
// on message
worker.onmessage = function(e) {
// e.data == 'msg from worker'
};
17
Restrictions
• !file:// (chrome)
• http: | https: && data: | javascript:
18
Browser Support
✔
3.5+
✔
4.0+
✔ ✔
4.0+
10.6+
X
19
Use Cases
• Prefetching and/or caching data for later use
• Code syntax highlighting or other real-time text
formatting
• Spell checker
• Background I/O or polling of webservices
• Processing large arrays or JSON responses
20
DEMO
21