The Coders Blog
The Coders Blog Author of The Coders Blog. Also a professional fullstack javascript developer working with various tech company and client around world.

What is web workers & it's implements in JavaScript?

Feb 22, 2019 · 2 minutes
What is web workers & it's implements in JavaScript?

Web workers is API in JavaScript which enables JavaScript code to run on background. In simple word, it is a piece of code which will execute in background as separate process and pass a result to DOM using message passing API to listener. (Lister is a function who listen to event from worker in main.js file.) In addition, they can perform I/O using XMLHttpRequest.

Why we need web hooks ?

If you already don't know, JavaScript is single threaded. It implies that noting can run parallel at same time in JavaScript environment. This is where asynchronous code and event loop comes into play. But Web Worker, brings possibility of parallel execution inside the browser in JavaScript code.

What about Browser Support?

In short, web workers has good support to major browsers. They are supported by latest browser such as Chrome version above 52 , Firefox version above 53, IE 10, Android, Safari 8 & above, all opera mini.

Quick check can be done in browser console
 typeof Worker || false
 
 "function"  // should return function. If false browser does not support it.

Initializing Web Worker.

You can initialize web worker as follow.

    const worker = new Worker('worker.js');
It create a object using a constructor, that run a named JavaScript file. The most important thing worker run on another global scope. Thus, using the window shortcut to get the current global scope (instead of self) within a Worker will return an error.

So, its run's on another scope. How to communicate with Web Worker ?

Here are two main ways:
  1. postMessage API by Web Worker object
  2. Channel Messaging API

Method 1: With postMessage API.

We can send message from main program ie. index.js to worker.js as follow:

In index.js

  const worker = new Worker('worker.js')
  worker.postMessage('hello World') 

In worker.js

  worker.onmessage = e => {
  console.log(e.data)
  }

  worker.onerror = e => {
    console.error(e.message)
  }

Sending message back from worker.

Worker can send message back to index.js using pushMessage() api.

In worker.js

worker.onmessage = e => {
  console.log(e.data)
  worker.pushMessage('hey there')
}

worker.onerror = e => {
  console.error(e.message)
}

In index.js

const worker = new Worker('worker.js')
worker.postMessage('hello')

worker.onmessage = e => {
  console.log(e.data)
}

Method 2: With Channel Messaging API

index.js

const worker = new Worker('worker.js')
const messageChannel = new MessageChannel()
messageChannel.port1.addEventListener('message', e => {
  console.log(e.data)
})
worker.postMessage(data, [messageChannel.port2])

worker.js

self.addEventListener('message', e => {
  console.log(e.data)
})

Terminating Web Workers

A web workers can terminated using terminate() in index.js. Also they provide method .close() in web worker itself.

Web Worker can load libraries using import script.
importScripts('../utils/file.js', './something.js')

Limitation while using Web Worker

  1. DOM cannot be excess: the Window object and the Document object are undefined.
  2. Messaging is primary and only way to communicate back with the main JavaScript.
  3. they need to be loaded from the same origin (domain, port and protocol)
  4. Page using file protocol (File://) cannot excess them.
Here is working implementation