DEV Community

loading...
Cover image for Introduction to Web Workers aka Multi-Threading in browser

Introduction to Web Workers aka Multi-Threading in browser

arunmurugan78 profile image Arun Murugan ・3 min read

Introduction

Web Workers are scripts which run in a separate thread in the background.

Web Workers are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface. (from MDN docs)

Javascript is a single threaded programming language, which means it runs instructions step by step sequentially.
If the code is executing some expensive task which takes a lot of time. Then, no other javascript code can execute until the control comes out of that step. This is because the current thread is busy executing that step and javascript is a single threaded language.
While that step is being executed, no javascript can execute making the UI un-responsive for task requiring javascript, which is obviously a bad user experience.

We wouldn't have faced this problem if javacsript was multi-threaded. It's not though. What if we can create threads using the web browser? ....Web Workers were born.

Each Web Worker runs in a separate OS thread and execution context.

Lets Start Coding!

// Check if the Web Workers are supported by the browser
if (window.Worker) {
  // Create a new Web Worker
 //Pass the URI of the script which has to run as a web worker to the Worker Constructor
  const myWorker = new Worker('worker.js'); 
}
Enter fullscreen mode Exit fullscreen mode

Inside the worker script (worker.js in this case) can be as simple as a console.log

console.log("Running in a separate thread");
Enter fullscreen mode Exit fullscreen mode

The main and the worker threads interact through Messages.

self in the web worker refers to the Worker Execution Context instance. We'll come back to self later again.

Sending Messages

We send message from main thread to worker thread through postMessage method of the worker.
Message from the worker script can be sent to main thread by simply calling postMessage(message) or self.postMessage(message)

Listening to Messages

The onmessage method of the worker instance fires when that worker has sent a message to the main thread.
The self.onmessage or onmessage function in the worker script fires when the main thread has sent a message.
The onmessage event listener function accepts a instance of MessageEvent.

app.js

const myWorker = new Worker('worker.js'); 
console.log("[Inside Main thread] Sending Message to Worker thread");
myWorker.postMessage("Hello Web Worker");
myWorker.onmessage = function (message) {
  console.log("[Inside Main thread] Message sent by Web Worker - ",message.data);
}
Enter fullscreen mode Exit fullscreen mode

worker.js

//onmessage is implicitly self.onmessage
onmessage = function (message){
  console.log("[Inside WebWorker] Message sent by Main thread - ", message.data);
 console.log("[Inside WebWorker] Sending Message to Main Thread");
  postMessage("Hello Main Thread");
}
Enter fullscreen mode Exit fullscreen mode

Output ( Console logs )

[Inside Main thread] Sending Message to Worker thread
[Inside WebWorker] Message sent by Main thread - Hello Web Worker
[Inside WebWorker] Sending Message to Main Thread
[Inside Main thread] Message sent by Web Worker - Hello Main Thread
Enter fullscreen mode Exit fullscreen mode

You can't access all Browser API inside the web worker script and that's for good. You have access to browser Api like IndexedDB, Web Sockets, inside the web worker. You can't directly manipulate or access DOM. Complete list of Browser api supported inside web worker.

Types of Web Workers

  • Dedicated Web Worker (What we saw earlier)
  • Shared Web Worker

Dedicated Web Worker

The web worker instance can be accessed only by the script created it.

Shared Web Worker

The web worker instance can be accessed by any script.

Further Readings

Learn more about Web Workers from MDN docs

Discussion (0)

pic
Editor guide