220 likes | 452 Views
WEB WORKERS. Amitesh Madhur (amitesh@yahoo-inc.com) ( Exceptional Performance, Bangalore). var worker = new Worker(‘MyWork.js'); worker.addEventListener ('message', function(e) { document.getElementById (‘heading'). textContent ( e.data ); }, false); worker.postMessage (‘WEB WORKERS');.
E N D
WEB WORKERS Amitesh Madhur (amitesh@yahoo-inc.com)(Exceptional Performance, Bangalore) var worker = new Worker(‘MyWork.js'); worker.addEventListener('message', function(e) { document.getElementById(‘heading').textContent(e.data);}, false); worker.postMessage(‘WEB WORKERS'); • onmessage = function(e) { • postMessage(e.data); • }
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 for(;;;) { // Perceived performance of the UI } • UI Blocked for 100 milliseconds == Perceived performance page is slow50 milliseconds….
What is Web Worker? serialize unserialize worker.postMessage(obj || str) HeavyComputation FormatData MAIN PAGE MAIN PAGE self.postMessage(obj || str) MAIN PAGE serialize unserialize
Without Web Workers • With Web Workers • What are Web Workers • Worker Environment • Subworkers/Delegation • Inline Worker • Restrictions • Browser Support • Use cases • Demo AGENDA • onmessage = fn{} • setTimeout(); • worker.postMessage('Hello World'); • worker.postMessage(obj);self.postMessage(e.data);
Without Web Workers Chrome Internet Explorer Firefox
With Web Workers Chrome Internet Explorer Firefox
What are Web Workers? • Scripts running in background. • Heavy Weight Scripts.
What are Web Workers? myworker.js // create web worker worker.postMessage({‘cmd’:gen_num}); self.onmessage = fn(e){} worker.onerror = fn(e){ // e.lineno // e.filename // e.message } // task completed self.postMessage(arrayOfRandomNum); worker.terminate(); worker.onmessage = fn(e){ // update DOM with e.data }
Difference from other approach. • How different from setTimeout? • How different from AJAX?
So what does Worker look like? Main Page // Check if workers are supported. if (typeof(Worker) == "undefined") { document.getElementById(‘support’).textContent = ‘Your browser does not support Web Workers’; return false; } // worker object var worker = new Worker('worker.js'); // post message to worker worker.postMessage(‘Are you there?’); // 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; } 1 2 3 4 5
So what does Worker look like? worker.js 1 self.onmessage = function(event){ postMessage(event.data + ‘ Worker says: Yes I am here.’); } OR self.addEventListener('message', function(e) { self.postMessage(event.data +‘ Worker says: Yes I am here.’); }, false); 2
Worker Environment • No BOM • No DOM • !parent • setTimeout, setInterval • navigator object • location object (read-only) • XMLHttpRequest • Spawning other web workers
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).
Subworker/Delegation Parent Worker self.onmessage = function(event){ varnum_workers = 4; // total sub workers varpending_workers = num_workers; // loop though the sub-workers for (vari = 0; i < num_workers; i++) { var worker = new Worker('subworker.js'); worker.postMessage(event.data); // on message worker.onmessage = function(event) { varstr += event.data; // collect data pending_workers -= 1; // workers pending // case: all response collected then post to main page if (pending_workers == 0) self.postMessage(str); } // on message sub-worker end } // loop end } 1 2 3 4
Subworker/Delegation subworker.js onmessage = function(event){ postMessage(event.data + ‘ Sub Worker says: Yes I am here.’); }
Inline worker • Worker script on the fly • Without creating separate worker file • BlobBuilder interface
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'); }"); varblobURL = 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' };
Restrictions • !file:// (chrome) • http: | https: && data: | javascript:
Browser Support 3.5+ ✔ ✔ ✔ ✔ • 4.0+ • 4.0+ • 10.6+ X
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
DEMO var worker = new Worker(‘MyWork.js'); worker.addEventListener('message', function(e) { document.getElementById(‘heading').textContent(e.data);}, false); worker.postMessage(‘DEMO'); • onmessage = function(e) { • postMessage(e.data); • }