The Web

beyond websites

István Szmozsánszky "Flaki"

@slsoftworks

JavaScript Developer

Mozilla Contributor
&
Community TechSpeaker

Tessel Project
Team Member

Frontend Trainer at
DPC Consulting

New standardized browser APIs

Offline: Cache API, indexedDB

Sensors: Geolocation, Battery, Accelerometer

Hardware: Web Bluetooth, Web NFC

Authentication: Credentials API

What are service workers?

    A kind of clientside server, scriptable proxy —    worker script tied to the origin, rather the page.

Promises (ES 2015) & Fetch API (DOM)

Easier handling of async network requests - and async callbacks in general.

Arrow functions (ES 2015)

fetch("data.json").then(function(p) {
  return p.json();
} ).then( function(c) {
  console.log(c);
});

fetch("data.json")
  .then( p => p.json() )
  .then( c => console.log(c) );
a => x

(a, b) => { return x; });

(function(a, b) { return x; }).bind(this);

The service worker life cycle

bitsofco.de/the-service-worker-lifecycle

// Note: ONLY HTTPS!
navigator.serviceWorker.register('/serviceworker.js', {

  // Service Worker events are scoped
  // to this subfolder only
  scope: '/trained-to-thrill/'

}).then(function(reg) {
  console.log('Service Worker on line!');

}, function(err) {
  console.log('Oops, Service Worker installation failed!');

});

event.waitUntil

self.addEventListener('push', function(event) {
  console.log('Received a push message', event);

  var title = 'Yay a message.';
  var body = 'We have received a push message.';
  var icon = '/images/icon-192x192.png';
  var tag = 'simple-push-demo-notification-tag';

  event.waitUntil(
    self.registration.showNotification(title, {
      body: body,
      icon: icon,
      tag: tag
    })
  );
});

Inside the SW script

// The SW will be shutdown when not in use to save memory,
// be aware that any global state is likely to disappear

console.log("SW startup");

self.addEventListener('install', function(event) {
  console.log("SW installed");
});

self.addEventListener('activate', function(event) {
  console.log("SW activated");
});

self.addEventListener('fetch', function(event) {
  console.log("Caught a fetch!");
  event.respondWith(new Response("Hello world!"));
});

importScripts

importscripts("my-script-file.js");

// the rest of the serviceworker.js, handling fetch, push, etc...

Event Handling:
fetch / push / sync / messages

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        const networkResponse = fetch(event.request)
          .then(fetchResult => {
            cache.put(event.request, fetchResult.clone());
            return fetchResult;
          });

        return response || networkResponse;
      })
  );
});

cache management

the offline cookbook

 

jakearchibald.com/2014/offline-cookbook

cache-first

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(response => response || fetch(event.request))
  );
});

network-first

self.addEventListener('fetch', function(event) {
  event.respondWith(
    fetch(event.request)
      .catch(ex => caches.match(event.request))
  );
});

bringing out the big guns

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        const networkResponse = fetch(event.request)
          .then(fetchResult => {
            cache.put(event.request, fetchResult.clone());
            return fetchResult;
          });

        return response || networkResponse;
      })
  );
});

Synthetic Responses

self.addEventListener('fetch', function(event) {
  if (event.request.url.match(/hello/i)) {
    event.respondWith(
      new Response("Hello world!")
    );
  }
});

...and so much more!
 

Server push emulation, appcache polyfills, JS transpiling and on-demand feature polyfilling, webserver-in-the-client, differential resource updates...

Support?

Chrome, Firefox, Opera, Samsung Internet, Edge...

Constantly evolving standard

NOT just for offline webapps

Lie-fi: When you are supposed to be online, but not.
Downtime: Maintenance, downtime, zombie apocalypse.
Performance: Any byte not downloaded is a byte saved.

...or Bandwidth caps:

But we need your help!

Service workers aren't a magic wand:

"With ServiceWorker we gave up trying to solve offline, and gave developers the moving parts to go solve it themselves."

Thank you!

GET IN TOUCH!
 

Made with Slides.com