• Live in the browser: Web Workers API (JS).
  • Separate from main thread (worker thread).
  • Threads communicate by posting/receiving messages.
  • Compute in the background.
  • Keep the user interface reactive.

What are Web Workers?

/* index.js */

// instantiate worker
const worker = new Worker('webWorker.js');

// send a message to the worker
const message = { sayHi: 'Hello worker!' };
worker.postMessage(message);
 
// listen to messages from the worker
worker.onmessage = event => console.log(event.data.acknowledgment);
/* webWorker.js */

// listen to messages from main thread
onmessage = event => {
    console.log(event.data.someData);
    // send a message to main thread
    const response = { acknowledgment: true };
    postMessage(response);
};
  • Resize/process images.
  • Generate large CSV files.
  • Convert files to another format.
  • Zip or unzip files.
  • HTML to PDF.

Some use cases

Pitfalls

  • No access to the DOM (worker scope).
  • Consume more resources (mobile devices).
  • Slower performances. Doing the same operation in workers will take longer than in the main thread.

Bundle up!

Webpack plugin: Use worker-loader to optimize your workers.

  • Get all the goodness from Webpack (minimizing, uglifying, code splitting, etc.)
  • Worker not be served as a separate public file. No need to figure out its location when you instantiate your worker.

 

Web Worker Workshop:
Get your hands dirty!

Made with Slides.com