Web Workers

I like the way you work it

@nolanlawson

@nolanlawson

photo of Nolan Lawson
pouchdb

The web! ❤️

The web has a problem :(

Every line of frontend JS you've ever written has (momentarily) stopped your page from working.

60 frames per second (FPS)

1000ms / 60 frames = 16.7ms

Factor in browser overhead...

Paul Lewis, 10ms
Jeff Atwood, state of JS performance is poor

WEB WORKERS!

// index.js

var worker = new Worker('worker.js');
worker.postMessage('ping');
worker.onmessage = function (e) {
  console.log(e.data); // 'pong'
};
// worker.js

self.onmessage = function (e) {
  console.log(e.data); // 'ping'
  self.postMessage('pong');
};

UI thread (main thread)

500KB JavaScript app

Four cores

What can Web Workers do?

  • Standard JavaScript
  • JSON
  • btoa(), atob()
  • FileReader, Blob, ArrayBuffer

What can Web Workers do? (cont.)

  • IndexedDB

IndexedDB (async!) blocks the DOM

What can Web Workers do? (cont.)

  • AJAX/fetch

Ajax (async!) blocks the DOM

What can Web Workers do?

  • JavaScript
  • JSON
  • IndexedDB
  • AJAX
  • ...but not DOM 😢
  • Virtual DOM!
pokedex.org virtual dom architecture

Pokedex.org on a 2011 Galaxy Nexus

Without workers

With workers

Pokedex.org bundle sizes

main.js24.1kB
worker.js90.9kB
serviceWorker.js15.8kB

React with Web Workers

Angular 2 - without Web Workers

Angular 2 - with Web Workers

This is coming to frameworks

Angular 2

React

Ember

Final thoughts

caniuse.com page for web workers

Four cores

Four cores

Thank you!

@nolanlawson

nolanlawson.github.io/empire-2016