All Projects → wildhaber → offline-first-sw

wildhaber / offline-first-sw

Licence: MIT license
Service worker example with 404 handling, custom offline page and max TTL for specific file types.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to offline-first-sw

Parcel Plugin Sw Cache
📦👷 Parcel plugin for caching using a service worker
Stars: ✭ 45 (-45.12%)
Mutual labels:  service-worker, offline-first
Workbox
📦 Workbox: JavaScript libraries for Progressive Web Apps
Stars: ✭ 10,434 (+12624.39%)
Mutual labels:  service-worker, offline-first
Beer
The source code for the Progressive Beer app!
Stars: ✭ 73 (-10.98%)
Mutual labels:  service-worker, offline-first
Offline Plugin
Offline plugin (ServiceWorker, AppCache) for webpack (https://webpack.js.org/)
Stars: ✭ 4,444 (+5319.51%)
Mutual labels:  service-worker, offline-first
Offline First
🔌 Everything you need to know to create offline-first web apps.
Stars: ✭ 2,792 (+3304.88%)
Mutual labels:  service-worker, offline-first
Upup
✈️ Easily create sites that work offline as well as online
Stars: ✭ 4,777 (+5725.61%)
Mutual labels:  service-worker, offline-first
Tetrys
𝌶 Tetris as Progressive Web Application
Stars: ✭ 100 (+21.95%)
Mutual labels:  service-worker, offline-first
jekyll-pwa-workbox
A Jekyll plugin using Workbox to make your PWA / Website available offline.
Stars: ✭ 22 (-73.17%)
Mutual labels:  service-worker, offline-first
Jfa Pwa Toolkit
⚡️ PWA Features to Any Website (very Fast & Easy)
Stars: ✭ 245 (+198.78%)
Mutual labels:  service-worker, offline-first
Ember Service Worker
A pluggable approach to Service Workers for Ember.js
Stars: ✭ 227 (+176.83%)
Mutual labels:  service-worker, offline-first
Sw Toolbox
A collection of tools for service workers
Stars: ✭ 3,649 (+4350%)
Mutual labels:  service-worker, offline-first
react-calculator
📐 PWA React + Redux Calculator
Stars: ✭ 65 (-20.73%)
Mutual labels:  service-worker, offline-first
Android Pwa Wrapper
Android Wrapper to create native Android Apps from offline-capable Progressive Web Apps
Stars: ✭ 265 (+223.17%)
Mutual labels:  service-worker, offline-first
Sw Precache
Service Worker Precache is a module for generating a service worker that precaches resources. It integrates with your build process. Once configured, it detects all your static resources (HTML, JavaScript, CSS, images, etc.) and generates a hash of each file's contents. Information about each file's URL and versioned hash are stored in the generated service worker file, along with logic to serve those files cache-first, and automatically keep those files up to date when changes are detected in subsequent builds.
Stars: ✭ 5,276 (+6334.15%)
Mutual labels:  service-worker, offline-first
angular-webpack-skeleton
This project is deprecated. Please refer to https://github.com/Ks89/angular-cli-skeleton
Stars: ✭ 16 (-80.49%)
Mutual labels:  service-worker, offline-first
Notepad
📒 An offline capable Notepad PWA powered by ServiceWorker
Stars: ✭ 100 (+21.95%)
Mutual labels:  service-worker, offline-first
Monitaure
🔔 A server uptime monitoring progressive web application - NO LONGER MAINTAINED
Stars: ✭ 135 (+64.63%)
Mutual labels:  service-worker, offline-first
nadya
subscription management done right
Stars: ✭ 14 (-82.93%)
Mutual labels:  service-worker, offline-first
affilicats
🐈 Progressive Web App demo that showcases flaky network resilience measures (📶 or 🚫📶).
Stars: ✭ 65 (-20.73%)
Mutual labels:  service-worker, offline-first
http2-examples-empireconf
HTTP2 examples for EmpireConf talk
Stars: ✭ 15 (-81.71%)
Mutual labels:  sw

Service Worker Example

offline first poster

Features

  • Custom offline page
  • Custom 404 page
  • Cache blacklist rules for resources that always comes from network
  • Individual TTL settings for different file extensions for a rolling cache refresh respecting offline-first
  • Easy to customize for your specific needs
  • Cleanup legacy cache on update
  • Automatic Caching of relative content defined with <link rel='index|next|prev|prefetch'>

Installation & Usage

Install the Service Worker

Simply copy sw.js in your root directory:

# simple wget-snippet or do it manually
# cd /your-projects-root-directory/
wget https://raw.githubusercontent.com/wildhaber/offline-first-sw/master/sw.js

and launch the Service Worker with the following snippet:

<script>
    if('serviceWorker' in navigator) {

        /**
         * Define if <link rel='next|prev|prefetch'> should
         * be preloaded when accessing this page
         */
        const PREFETCH = true;

        /**
         * Define which link-rel's should be preloaded if enabled.
         */
        const PREFETCH_LINK_RELS = ['index','next', 'prev', 'prefetch'];

        /**
         * prefetchCache
         */
        function prefetchCache() {
            if(navigator.serviceWorker.controller) {

                let links = document.querySelectorAll(
                    PREFETCH_LINK_RELS.map((rel) => {
                        return 'link[rel='+rel+']';
                    }).join(',')
                );

                if(links.length > 0) {
                    Array.from(links)
                        .map((link) => {
                            let href = link.getAttribute('href');
                            navigator.serviceWorker.controller.postMessage({
                                action : 'cache',
                                url : href,
                            });
                        });
                }


            }
        }

        /**
         * Register Service Worker
         */
        navigator.serviceWorker
            .register('/sw.js', { scope: '/' })
            .then(() => {
                console.log('Service Worker Registered');
            });

        /**
         * Wait if ServiceWorker is ready
         */
        navigator.serviceWorker
            .ready
            .then(() => {
                if(PREFETCH) {
                    prefetchCache();
                }
            });

    }
</script>

For AMP-Pages use:

<script async custom-element="amp-install-serviceworker" src="https://cdn.ampproject.org/v0/amp-install-serviceworker-0.1.js"></script>
<amp-install-serviceworker
	src="/sw.js"
	data-iframe-src="https://ampbyexample.com/sw.html"
	layout="nodisplay">
</amp-install-serviceworker>

Get more information for AMP-Install-Serviceworker at ampbyexample.com

Install the manifest.json

The manifest is an important part but not required. Read more about manifest.json on Google Developers.

Copy the manifest.json into your root directory and link it within your markup.

# simple wget-snippet or do it manually
# cd /your-projects-root-directory/
wget https://raw.githubusercontent.com/wildhaber/offline-first-sw/master/manifest.json

And create the following link-snippet within your page's <head>-Section:

<link rel="manifest" href="/manifest.json">

Configuration

Service Worker

CACHE_VERSION { number }

const CACHE_VERSION = 1;

The CACHE_VERSION is important when you update your service-worker. The cache-location will be updated and the old legacy cache is getting deleted.

BASE_CACHE_FILES { array }

const BASE_CACHE_FILES = [
    '/style.css',
    '/script.js',
    '/search.json',
    '/manifest.json',
    '/favicon.png',
];

Define files that in this list which always needs to be cached from the beginning.

OFFLINE_CACHE_FILES { array }

const OFFLINE_CACHE_FILES = [
    '/style.css',
    '/script.js',
    '/offline/index.html',
];

Define files necessary for your offline page.

NOT_FOUND_CACHE_FILES { array }

const NOT_FOUND_CACHE_FILES = [
    '/style.css',
    '/script.js',
    '/404.html',
];

Define files necessary for your 404 page.

OFFLINE_PAGE { string }

const OFFLINE_PAGE = '/offline/index.html';

Deliver this page when the user is offline and the page is not cached already.

NOT_FOUND_PAGE { string }

const NOT_FOUND_PAGE = '/404.html';

Deliver this page when the user lands on a page with Status-Code >= 400.

MAX_TTL { object }

const MAX_TTL = {
    '/': 3600,
    html: 3600,
    json: 86400,
    js: 86400,
    css: 86400,
};

This is a key-value mapping file extensions with a certain maximal time-to-live (in seconds not milliseconds). This is how long the chache will be active until the page is getting refreshed from the network.

Not specified extensions with stay cached until a SW-Update.

// 60 = 1 minute
// 3600 = 1 hour
// 86400 = 1 day
// 604800 = 1 week
// 2592000 = 30 days (~ 1 month)
// 31536000 = 1 year

CACHE_BLACKLIST { array}

const CACHE_BLACKLIST = [
    (str) => {
	    // str = URL of the resource
	    // apply this rule when you do not want to cache external files
        return !str.startsWith('https://yourwebsite.tld');
    },
];

This is a list of functions a URL gets checked against if it should be cached or not. If one method returns true this resource will not be cached.

SUPPORTED_METHODS { array }

const SUPPORTED_METHODS = [
    'GET',
];

Only methods in this list will be cached.


MIT License

Copyright (c) 2017 Raphael Wildhaber, https://github.com/wildhaber/

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].