Hi, I am Trishul

Taking web offline

 

 

  

@trishulgoel

SERVICE WORKERS

WHAT

@trishulgoel

BUILDING BLOCKS OF PWA

@trishulgoel

WHY

@trishulgoel

  • FASTER LOAD TIME

  • OFFLINE BROWSING

  • PUSH NOTIFICATIONS

  • BACKGROUND SYNC

APP LIKE EXPERIENCE

@trishulgoel

PREREQUISITES

@trishulgoel

- HTTPS

- Browser Compatibility

@trishulgoel

HOW

@trishulgoel

if ('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
        navigator.serviceWorker.register('/serviceworker.js').then(function(registration) {
          // Registration success
        }, function(err) {
          // Registration fail
        });
    });
}

REGISTER SERVICEWORKER

@trishulgoel

LIFE CYCLE

@trishulgoel

@trishulgoel

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open('my-cahce').then(function(cache) {
      return cache.addAll(
        [
          '/css/style.css',
          '/js/script.js',
          '/index.html'
        ]
      );
    })
  );
});

INSTALLING SERVICEWORKER

@trishulgoel

self.addEventListener('activate', function(event) {
    event.waitUntil(
        caches.keys().then(function(cacheName) {
            return Promise.all(
                cacheName.filter(function(name) {
                    return name !== 'my-cache';
                }).map(function(name) {
                    return caches.delete(name);
                })
            )
        })
    )
});

ACTIVATING SERVICEWORKER

@trishulgoel

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        if (response) {
          return response;
        }
        return fetch(event.request);
      }
    )
  );
});

FETCH / MESSAGE

@trishulgoel

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.open('cahce-key').then(function(cache) {
      return fetch(event.request).then(function(response) {
        cache.put(event.request, response.clone());
        return response;
      });
    })
  );
});

In service worker

@trishulgoel

PUSH NOTIFICATIONS

@trishulgoel

self.addEventListener('push', function (event) {
  if (event && event.data) {
    self.pushData = event.data.json();
    if (self.pushData) {
      event.waitUntil(self.registration.showNotification(self.pushData.title, {
        body: self.pushData.body,
        icon: self.pushData.data ? self.pushData.data.icon : null
      }).then(function() {
        clients.matchAll({type: 'window'}).then(function (clientList) {
          if (clientList.length > 0) {
            messageToClient(clientList[0], {
              message: self.pushData.body // suppose it is: "Hello World !"
            });
          }
        });
      }));
    }
  }
});

@trishulgoel

CACHING

@trishulgoel

CACHE API

NOT BROWSER CACHING

@trishulgoel

@trishulgoel

No Internet

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(cacheName).then(function(cache) {
      return cache.addAll(
        [
          '/css/style.css',
          '/js/script.js',
          '/index.html'
        ]
      );
    })
  );
});

ADDING FILES TO CACHE

@trishulgoel

USE CASES

@trishulgoel

CACHE ONLY

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

@trishulgoel

CACHE (Fallback Network)

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

@trishulgoel

NETWORK (Fallback Cache)

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

@trishulgoel

CACHE THEN NETWORK

caches.match('/data.json')
.then(response => {
    updatePage();
    fetch('/data.json').
    then(result => {
        updatePage();
    })
})
.catch(() => {
    fetch('/data.json').
    then(result => {
        updatePage();
    })
});

In page

@trishulgoel

CUSTOM RESPONSES

self.addEventListener('fetch', function(event) {
  event.respondWith(
    // Try the cache
    caches.match(event.request).then(function(response) {
      if (response) {
        return response;
      }
      return fetch(event.request).then(function(response) {
        if (response.status === 404) {
          return caches.match('/404.html');
        }
        return response
      });
    }).catch(function() {
      return caches.match('/offline.html');
    })
  );
});

@trishulgoel

REFERENCES

- https://serviceworke.rs

- https://developer.mozilla.org

- https://developers.google.com/

@trishulgoel

@trishulgoel

@trishulgoel

Service workers

By Trishul Goel

Service workers

Take the web offline with service workers

  • 878