Web Workers

Shota Papiashvili

Jun 5 2017

But Wait, There’s More

What?

What?

Simple Web Worker

each instance of our page (tab) will have its own web worker

Shared Web Worker

one worker will serve all of our tabs, each tab can publish a message to the worker

Web worker is not a service worker

What?

Why?

  • Concurrent (parallelism) - not async
  • Threading - not single thread any more
  • Shared Workers - can serve multiple connections (tabs)
  • Good support among browsers
  • The UI stays responsive
  • Access to XHR, Navigator, Location (read-only), setTimeout/Interval, App Cache, Import Scripts
  • JSON messaging format

When?

  • Prefetching/caching data for later use
  • Spell checker
  • Analyzing video/audio data
  • Background I/O or polling of webservices
  • Processing large arrays or humungous JSON
  • Image filtering in <canvas>
  • Updating many rows of a local web database

How? - simple

var worker = new Worker('worker.js');

worker.addEventListener('message', function(e) {
  console.log('Worker said: ', e.data);
}, false);

worker.postMessage('Yo'); 
self.addEventListener('message', function(e) {
  console.log(e.data);
}, false);

app

worker

How? - shared

var worker = new SharedWorker("worker.js");
worker.port.addEventListener("message", function(e) {
	console.log('Worker said: ', e.data);
}, false);
worker.port.start();
worker.port.postMessage("Yo");
self.addEventListener("connect", function (e) {
	var port = e.ports[0];

	port.addEventListener("message", function (e) {
		port.postMessage("Hello " + e.data + ")");
	}, false);

	port.start();
}, false);

app

worker

Demo

The use case that I will demo is a web site that users attend to open multiple tabs of (like online mailbox)

 

The objective is to cache the users data and share it among all of the tabs

Demo

All the code is at: https://github.com/shotap/webworkers-demo

Thank You!

Shota Papiashvili

Jun 5 2017

@shotapa          shotap

Made with Slides.com