Introduction
The Web Workers specification defines an API for running computationally intensive code in a thread other than the web application user interface.
The Web Workers specification defines an API for running computationally intensive code in a thread other than the web application user interface.
Long tasks can run without affecting your interface’s memory and CPU footprint because the Worker will live in its own thread.
Consider Web Workers for the following tasks
• Encoding/decoding a large string
• Complex mathematical calculations (e.g., prime numbers, encryption, simulated
annealing, etc.)
• Sorting a large array
• Network requests and resulting data processing
• Calculations and data manipulation on local storage
• Prefetching and/or caching data
• Code syntax highlighting or other real-time text analysis (e.g., spell checking)
• Image manipulation
• Analyzing or processing video or audio data (including face and voice recognition)
• Background I/O
• Polling web services
• Processing large arrays or huge JSON responses
Creating a worker
var worker = new Worker(<URI of a javascript file>);
/*
Loads the scriptExecutes it in the background
*/
var worker = new Worker("worker.js");
/*
Get the result back
*/
worker.onmessage = function(event)
{
{
console.log("result is here");
}
(or)
worker.addEventListener('message', function(event)
{
console.log("result is here")
});
/*
start the worker
*/
{
console.log("result is here")
});
/*
start the worker
*/
worker.postMessage();
Limitations
Worker Execution
Web Workers listening for messages run forever
Web Workers perform a single task and exit
Detecting if the browser supports Web Workers
Workers don’t have access to the DOM of the “parent” page.
They don't have access to
• The window object
• The document object
• The parent object
• And, last but not least, they can’t use JavaScript libraries that depend on these
objects to work, like jQuery.
Features they can use are:
• The navigator object
• The location object (read-only)
• The XMLHttpRequest function
• The atob() and btoa() functions for converting Base 64 ASCII to and from binary
data
• setTimeout() / clearTimeout() and setInterval() / clearInterval()
• dump()
• The application cache
• External scripts using the importScripts() method
• Spawning other Web Workers
Worker Execution
Web Workers listening for messages run forever
Web Workers perform a single task and exit
Detecting if the browser supports Web Workers
if (Modernizr.webworkers) {
// window.Worker is available!
} else {
// no native support for Web Workers
}
Starting chrome from command line on mac
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files
Messages sent between our web app page and the Web Worker using postMessage()
will be copied (not shared). The messages are in JSON format.
Loading External Scripts/ libraries into a Web Worker
To load external script files or libraries into a Web Worker, use the importScripts()
global function
importScripts('script1.js');
importScripts('script2.js');
or
importScripts('script1.js', 'script2.js'); //blocking call, waits until all scripts are fetched
Browser fetches them in any order. It throws NetworkError in case of any failure fetching.
After all are fetched, the scripts will be run in the order written.
callback functions in importScripts
Calling Twitter API and setting a call back that will handle data Twitter returns.
importScripts('http://twitter.com/statuses/user_timeline/' +
user + '.json?count=10&callback=processTweets');
.
.
function processTweets(data) {
// parse the json object that holds the tweets and build a html block from
// their content.
.
.
}
Dedicated Web Workers
Runs scripts in background threads
Communicates with its web app by posting messages to an event handler registered with the web app that spawned it.
Supports two events:
onmessage: triggered when a message is received.
onerror: triggered when an error occurs in the Worker thread.
Runs scripts in background threads
Communicates with its web app by posting messages to an event handler registered with the web app that spawned it.
Supports two events:
onmessage: triggered when a message is received.
onerror: triggered when an error occurs in the Worker thread.