Web Workers

Web workers provide a standard way for browsers to run JavaScript in the background. With web workers, you can spawn multiple “threads” that all run at the same time, more or less. (Think of how your computer can run multiple applications at the same time, and you’re most of the way there.) These “background threads” can do complex mathematical calculations, make network requests, or access local storage while the main web page responds to the user scrolling, clicking, or typing.

Checking for web workers uses detection technique #1 (see Detection Techniques). If your browser supports the Web Worker API, there will be a Worker property on the global window object. If your browser doesn’t support the Web Worker API, the Worker property will be undefined. This function checks for web worker support:

function supports_web_workers() {
  return !!window.Worker;
}

Instead of writing this function yourself, you can use Modernizr (see Modernizr: An HTML5 Detection Library) to detect support for web workers:

if (Modernizr.webworkers) {
  // window.Worker is available!
} else {
  // no native support for web workers :(
  // maybe try Gears or another third-party solution
}

Note that JavaScript is case-sensitive. The Modernizr attribute is called webworkers (all lowercase), but the DOM object is called window.Worker (with a capital “W” in “Worker”).

Get HTML5: Up and Running now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.