Giter VIP home page Giter VIP logo

pwa-web-app's Introduction

pwa-web-app

Pre-requisites

  • Node JS (v 11+ preferred)
  • http-server ( Run npm install http-server -g in your terminal/commandline)

How to start the application

  • Run http-server
  • Go to your browser and type localhost:8080

What is a Service Worker?

  • A JS script that gets registered with the browser.
  • Stays registered with the browser even when offline.
  • Can load content even with no connection.
  • They cannot directly access the DOM.
  • Programmable network proxy.
  • Terminated when not being used.
  • Make use of promises.
  • Require HTTPS unless you're on localhost

Normal Request & Response

Browser -> Remove Server

  • Requests just go to a remote server.

With Service Worker

Browser -> Service Worker -> Remote Server

  • When you have a service worker registered. All requests pass through the service worker to the remote server and the same is for the response through the service worker to the browser.

  • The reason for this is that the service worker intercepts the request and decides what to do with the request. There are a few strategies that can be applied to service workers and how to deal with requests and so, these strategies are applied and executed when the service worker intercepts requests. One example could be applying a network-first strategy. This strategy is triggered when the service worker intercepts the request from the browser.

Use Cases

  • Caching assets & API calls.
  • Push Notifications (Push & Notification API).
  • Background data sync/preload.
  • Used in progressive web apps.

Service Worker Lifecycle & Events

  • REGISTER -> INSTALL -> ACTIVATE
  • INSTALL: Triggers install event.
  • ACTIVATE: Triggers activate event.
  • Service workers can receive message events and functional events such as:
    • fetch
    • push - for example used for push notifications
    • sync - for the background sync api.

Browser Supprt

Register Service Worker

In our main.js file we can register our service worker file to be used with our application. The service worker file we created is called sw_cached_pages.js and it is just a javascript file. However, all of our service worker logic will be implemented in that file. But before we do that, we have to register the service worker so that our browser will know that we are using a service worker.

In our main.js file we register the service worker as follows:

Check Service Worker support

Before we register a service worker, it's worth checking if the browser you are using supports service workers otherwise, all the work we will do will be done for nothing.

We can check if our browser support service workers by:

  • Checking the navigator object and check if serviceWorker exists.
  • Or is navigator.serviceWorker exists.
if ('serviceWorker' in navigator) {
    // Register Service Worker here ...	
}

or

if (navigator.serviceWorker) {
    // Register Service Worker here...
}

Register Service Worker

Once we have established that our browser support service workers, we can register our service worker file that will contain all of our service worker logic.

It is also important to note that we should think about the web event we would want to apply our script to register our service worker. In our case we would want to apply our script at the load event.

To do this we need to apply an EventListener as below:

if ('serviceWorker' in navigator) {
	window.addEventListener('load', () => {
            // Apply logic to register service worker here...
	});
}

Within our EventListener, we can now register our service worker as below:

if ('serviceWorker' in navigator) {
	// We want to register service worker when the window loads.
	window.addEventListener('load', () => {
		navigator.serviceWorker
			.register('../sw_cached_pages.js')
			.then(() => console.log('Service worker is registered.'))
			.catch(err => console.log(`Service Worker failed to register: ${err}`));
	});
}

Note that it is a promise so we can apply logic after the promise is resolved successfully by using the then() method. Should the promise fail for any reason, we can apply logic after the promise failure in the catch() method.

sw.js

Service Worker Install Lifecycle

We can apply logic to be executed in the install lifecycle of a service worker. We have to apply it in an eventlistener of the service worker as below:

// Call Install Event
self.addEventListener('install', (event) => {
	console.log('Service Worker Installed');
    // Apply logic here to be executed in the install lifecycle...
});

Service Worker Activate Lifecycle

We can also apply logic to be executed in the activate lifecycle of a service worker. We have to also apply this in an eventlistener of the service worker as below:

// Call Activate Event
self.addEventListener('activate', (event) => {
	console.log('Service Worker activated');
});

pwa-web-app's People

Contributors

artemas-muzanenhamo avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.