Frontend Scrapbook

Notes that make a difference

Web workers

By admin

on Wed Aug 26 2020

Browsers are running single threads in the treatment of generating your page and actions on the front end. computationally expensive javascript can result in unresponsive UI. Web workers help us solve this problem by offloading the computationally expensive job in a separate thread from the main UI.

Services workers cannot access DOM, because it is not thread-safe. The main thread and service worker can communicate with each other by attaching to ‘onmessage’ event and using postMessage to send/receive from.

//app.js
const worker = new Worker('/src/js/worker.js');
worker.postMessage("start"); //we can send any data
worker.addEventListener('message', (event) => {
  console.log(event.data); //'message received from app.js'
});
....
....
worker.terminate(); //terminate web worker when not used. 

//worker.js

self.onmessage = (event) => {
  console.log(event.data);
   self.postMessage("message received from app.js");
};

self.postMessage("this is a message from worker.js");