Chapter 2. How and Where Can We Use Web Workers?

When we wish to use a feature that is not supported in all browsers, we need to check for support. In our case, for Web Workers we need to check whether there is a Worker property on the global window object. If the browser does not support the Web Worker API, the Worker property will be undefined, and you will need to find another approach. (Hopefully you designed your application on a progressive enhancement model, and this won’t be fatal.) We can use this simple helper function to sniff for Web Workers support:

isWorkersAvailable() {
 return !!window.Worker;
}

Instead of using the function above, you could use the Modernizr library (http://modernizr.com) to detect whether the client’s browser supports Web Workers. This would let you test to see whether the client browser supports Web Workers and do something else if it doesn’t:

if (Modernizr.webworkers) {
 // window.Worker is available!
} else {
 // no native support for Web Workers
}

Now that we know that our browser can leverage Web Workers, let’s have a look at a simple example that calculates prime numbers, a popular “Hello World” of the Web Workers world, shown in Example 2-1 and Example 2-2. Figure 2-1 shows the results.

Example 2-1. highPrime.js, a brute force prime number calculator that can be used as a Web Worker

// // A simple way to find prime numbers // var n = 1; search: while (true) { n += 1; for (var i = 2; i <= Math.sqrt(n); i += 1) { if (n % i == 0) { continue search; ...

Get Web Workers 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.