Understanding Web Workers

Before getting to Web Workers, let us understanding the purpose for its need and how JavaScript works.

everything is single“,

  1. JavaScript will execute everything in a single thread.
  2. Each statement is added to a stack and will execute one-by-one.

The good thing is, our code will execute in a synchronous way. But the bad side is, rest of the statement in the stack has to wait if the current process takes a lot of time.

Performing heavy ‘client to server side’ task or huge data processing like JSON or complex calculations which going to taking a lot of time.

Eventually when we run this code, either it might freeze and become unresponsive or ends by blocking rest of the process (or both).

unresponsive

To solve this problem, we are going to use something called ‘Web Workers‘, which runs independently of any user interface. All the statements/code mentioned in ‘Web workers‘ will run in the background. Well, let’s get started.

  1. Need for Web Worker!
  2. What is Web Worker
  3. How it works
    • Creating a Worker
    • Web Worker Communication
    • Importing External Files
  4. Web Workers Example
  5. Stopping a Web Workers
  6. Handling Errors
  7. Security Concerns
  8. How to use & When to use
  9. Browser Compatibility

Consider the following example,

Not only it will take a lot of time to print the statement ‘end’… our browser freeze and hangs and you might end up killing the process.
Let’s see how the above code runs in Web Worker. To create a worker

and

Now, if you run this you won’t see any freezes at all! That’s the magic of the Web Worker.

So, What is Web Worker?

Web Worker provides a way to run the task in the background and independently of any user interface. We can put any long running tasks in workers which will not interrupt keyboard or mouse click events.

  • It enables to offload expensive operations
  • It includes separate message queue, event loop, and memory.

How it works

Creating Worker

Web Worker are created using the object Worker()

The new Worker('javascript_file.js') will look for a file named ‘javascript_file.js’ which will run independent thread from our actual code.

Web Worker Communication

To communicate to and fro from our worker we’ll use window.postMessage to pass messages.

Import External Files

Using importScripts you can import JavaScript files inside workers.

Let’s see an example, to understand all this stuff.

Web Workers example – Creating a simple Web Worker to poll for contents.

In this example, we will randomly fetch contents from Wikipedia periodically from workers in a nonblocking way.

First, let’s build the worker part and then create our index.html to link the worker. See the code below for explanation

Stopping Web Workers

Once our Web Worker is created, it will continue to listen for any changes using the event listeners, when it’s time to stop use the terminate command.

Handling Errors

The onerror event listeners we will attach the Web Workers for capturing any errors.

or simply

Security Concerns

Since Web workers use postMessage for communication, the origin needs to be checked on receiving the message.

https://security.stackexchange.com/questions/20022/how-to-use-postmessage-securely

Web Workers Limitations

Though awesome it seems there are some limitations with Web Workers.

  • You cannot access the DOM from web workers (I.e, No document, getElementById)
  • Cannot access global objects or functions on the main page
  • Workers have high start-up performance cost and high per-instance memory cost. So it’s best to use minimal amount of Web Workers
  • Communication to our application only be carried our using postMessage

Overall Web Worker is must use any high processing tasks, from web polling high data processing, it does’em all. But, know when to use Web worker and when not to. You don’t need to use it all the time. And finally, there are other types of Workers which will see it soon.

codelikeapoem_caniuse_web_worker

Reference

  1. https://gist.github.com/sk8terboi87/32699d5a3a9bcbdd10d7b94316f54ccd
  2. https://html.spec.whatwg.org/multipage/workers.html
  3. https://www.tutorialspoint.com/html5/html5_web_workers.html
  4. https://www.html5rocks.com/en/tutorials/workers/basics/
  5. http://ejohn.org/blog/web-workers/