Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Worker power!

Dan Gebhardt
September 16, 2019

Worker power!

Presentation about web workers from EmberCamp Chicago 2019.

Dan Gebhardt

September 16, 2019
Tweet

More Decks by Dan Gebhardt

Other Decks in Programming

Transcript

  1. Main thread • fetching, parsing, running JS • page layout

    • painting • observing user interactions • manipulating the DOM
  2. Concurrency is about dealing with lots of things at once.

    Parallelism is about doing lots of things at once. - Rob Pike
  3. I know it when I see it. - US Supreme

    Court Justice Potter Stewart Jacobellis v. Ohio, 1964
  4. • new and unproven • lack of browser support •

    lack of capabilities Challenges to using workers
  5. • awkward to use • awkward to test • lack

    of FE framework support ✅ ✅ ✅ DX Challenges to using workers
  6. !"# $%& '() *!" #$% &'( )*! • async communication

    • no shared memory • controlled lifetime • access to browser APIs such as IndexedDB, fetch, etc. • no access to the DOM Characteristics of all workers
  7. P R O G R E S S I V

    E W E B A P P C H E C K L I S T • Site is served over HTTPS • Pages are responsive • App URLs load while offline • Add to Home screen • Fast first load • And more ...
  8. S E R V I C E W O R

    K E R A B A C K G R O U N D S C R I P T T H AT A C T S A S A P R O X Y B E T W E E N Y O U R A P P L I C AT I O N A N D I T S E N V I R O N M E N T.
  9. // Register service worker if ('serviceWorker' in navigator) { window.addEventListener('load',

    function() { navigator.serviceWorker.register('/sw.js') .then(function(registration) { // Registration succeeded }, function(err) { // Registration failed }); }); } S E R V I C E W O R K E R / a p p . j s
  10. var CACHE_NAME = 'todo-dino-v1'; Var CACHE_URLS = ['/', '/app.js', '/app.css'];

    self.addEventListener('install', function(event) { // Install app shell event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { return cache.addAll(CACHE_URLS); }) ); }); S E R V I C E W O R K E R / s w. j s
  11. self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) // Check cache .then(function(response) {

    if (response) { return response; // Return from cache } return fetch(event.request); // Fetch if needed }) ); }); S E R V I C E W O R K E R / s w. j s
  12. Testing tips • Write modular code • Unit test your

    modules (w/o workers) • Stub workers in your app