HTML5 Web Workers for AJAX Requests
Sometimes you need to load and process a ton of data on the client-side, but how do you do that without blocking the UI? The problem with JavaScript on the browser is that it runs on a single thread. In other words, two scripts or processes cannot run simultaneously. If you are processing JavaScript after page load, the end user cannot interact dynamically with the page. The JavaScript will not handle UI events while processing something else. If you process something large before page load, the end user has to wait all-together which is a horrible user experience.
Running scripts asynchronously also does not help as non-blocking does not mean concurrency. So, how do you process two JavaScript functions at the same time? As the title suggests, HTML5 has Web Workers which bring threading to JavaScript and this post is going to show how to use web workers to not only process multiple scripts at the same time, but also make AJAX requests in Web Workers.
Using Web Workers in JavaScript is really simple. Here is a good starting point:
This was pretty much taken from a great article on Web Workers from html5rocks and this is all you need to bring concurrency to JavaScript. You don’t even need a separate file for Web Workers, that link shows how to use a Blob() to “inline” your worker in the same HTML file. Now, can a web worker script execute an Ajax request? It sure can. Here is a simple example of making a XMLHttpRequest in pure JavaScript:
So, let’s put it all together. I created a simple JavaScript animation running on the main thread while I initiate a Web Worker to make an Ajax request for a JSON file. The web worker retrieves and processes the JSON file in the background while the animation is still running. The worker return JSON object as string to the main thread and puts that string into a DOM element. Instead of using a really big JSON file (couple megabytes at last to see the non-blocking effect), I inserted a setTimeout event to add some latency into the Web Worker. Here is the demo of Web Workers and XHR request running concurrently.
It surprises me that Web Workers are not used more often these days but I have a feeling that will happen in the future.
External:
Debugging Web Workers in Chrome
Make your UI More Responsive
Speed up JavaScript apps with Web Workers
Web Workers 101
parallel.js – Parallel Computing with Javascript
Using Web Workers
Web Workers for image manipulation
Estimate the number of cores on your machine with web workers
New Tricks in XMLHttpRequest2
Catiline.js – JavaScript Library for workers
Concurrency in JavaScript