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

Web Worker(s); - Outsource your JavaScript

Web Worker(s); - Outsource your JavaScript

Sliedes from the talk I provided @BerlinJS, March 2018.

Avatar for Develoger

Develoger

March 21, 2018
Tweet

Other Decks in Programming

Transcript

  1. 1 .develoger { 2 transform: scaleY(-1); 3 } 4 5

    6 7 8 9 /* Senior Front-End Engineer && Technical Product Owner at SMAVA */ 10 /* blog at www.develoger.com */ 11 /* twitter @develoger */ 12 13
  2. if (window.Worker) || ‘why web workers?’ Single thread means single

    execution stack. No matter of the async nature of the web APIs such is setTimeout || XMLHttpRequest they are not multi-thread, just non blocking.
  3. SYNC CODE BLOCKS THE BROWSER That is obvious. But even

    if you postpone execution of some calculations that does not solves the problem, just delays the inevitable. Eg. doing JSON.parse(); immediately after the async action can instantly block the execution stack. Not to mention any other further data processing. In many cases such computation should be done from within the Worker.
  4. Taboo?! Web Workers should be taboo topic if you need

    to directly modify... DOM Window object Parent object
  5. Web workers are able to access... Navigator object { ...offline,

    online, userAgent } Location object { ...host, href } XMLHttpRequest
  6. Worker === serviceWorker // false Worker resides in the global

    scope (Window obj) and it can be instantiated with new Worker(); Many Workers per tab. Is VERY well supported! serviceWorker needs to be registered via navigator.serviceWorker.register(); One serviceWorker per origin (domain). No XMLHttpRequest, only fetch! It can be used as a proxy with full caching support. PWA depend on it heavily for providing the “offline” experience to the end user. It have limited support.
  7. ` WEB WORKERS ARE TALKABLE main context Hello… const worker

    = new Worker('webworker.js'); main context Here is piece of info… worker.postMessage({ ...data }); webworker I am listening… onmessage = event => { return process(event.data); } main context I will be waiting for the response… worker.onmessage = event => { console.log(event.data); }
  8. USE Repacking / reformatting of data-sets == lazy Back-End. Doing

    heavy calculations on the FE will endanger the UX, even if executed in the different thread. Since devices that run our JS apps are limited in resources. Multi-threading is not about lifting heavy weight. It’s about not blocking your main stack.