Improve Web Performance With Web Workers

nikhiltatpati

Nikhil

Posted on April 27, 2022

Improve Web Performance With Web Workers

If your are looking to optimise or improve performance of your web application then you should definitely use web workers but still many people are unaware of it and don't know how to setup with web application. In this post i'll do my best to help you with web workers.

What is Web Worker?

In simple terms web worker is nothing but a javascript file that is executed by the browser in background separate from your application javascript file.

How Web Worker can increase your application performance?

As Web worker runs separate from the main javascript file you can put your computational intensive functions present in main javascript file into web worker file so main thread can run smoothly with no hiccups in user interface.

How to setup web worker

Create a javascript file named worker.js as shown below in your project directory.


// worker.js
console.log("Hello from web worker!")
this.onmessage = e => {
  console.log('worker.js: Message received from main script', e.data)
  this.postMessage('Hello main')
}

Enter fullscreen mode Exit fullscreen mode

onmessage : It is used to listen to any messages sent by the main application thread.

postMessage : It is used send message to main application thread.

In main.js file you can instantiate worker object by passing worker.js path address to Worker class and then similarly you can use onmessage and postMessage function to communicate with the worker thread.

// main.js
const worker = new Worker('worker.js')
worker.postMessage('Hello Worker')
worker.onmessage = e => {
  console.log('main.js: Message received from worker:', e.data)
}
// if you want to "uninstall" the web worker then use:
// worker.terminate()

Enter fullscreen mode Exit fullscreen mode

You can use worker.terminate() function to terminate your web worker execution.

With this simple steps now you can put your compute intensive functions in web worker and communicate with main application thread once it's executed.

Thank you for reading this article. Follow me on Twitter if you are interested in web development and javascript content.

💖 💪 🙅 🚩
nikhiltatpati
Nikhil

Posted on April 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related