Precache assets using wordbox

Partha Sai Guttikonda
3 min readJul 24, 2021

--

This article is about pre cached assets like images, videos, etc saved to user browser’s cache storage.(vue.JS, pwa and service-worker.js)

Photo by Florian Krumm on Unsplash

About WorkBox

  • Workbox is a set of libraries that can power a production-ready service worker for your Progressive Web App.
  • Prerequisites →During development you’ll be able to use service worker through localhost, but to deploy it on a site you'll need to have HTTPS setup on your server.
  • vue.JS provides the pwa by @vue/cli-plugin-pwa . (We can add pwa to already existing project by running this command→vue add pwa). https://www.npmjs.com/package/vue-cli-plugin-pwa

Introduction:

  • There are two ways to pre-cache in workbox
    1. generateSW(generates service-worker.js for use)
    2. InjectManifest(We will write our own service-worker.js)
  • If we don’t want to cache media assets and endpoint responses then we can go with generateSW.
  • Using InjectManifest, we have five strategies of cache
    1. Stale-While-Revalidate
    2. Cache First
    3. Network First
    4. Network Only
    5. Cache Only
Stale-While-Revalidate
CacheFirst(Cache Falling Back to Network)
Network First (Network Falling Back to Cache)
Network Only
Cache Only

Step 1:

  • we will config pwa inside vue.config.js
  • In this step we will select the workboxPluginMode →InjectManifest
vue.config.js

If you want to use generateSW replace workboxPluginMode to generateSW and skip to step3.

Note →The InjectManifest plugin will generate a list of URLs to precache and add that precache manifest to an existing service worker file. It will otherwise leave the file as-is.

Step 2:

  • Now we will create src/service-worker.js, Where we mention precaching urls.

Note:- If you want use different strategy in place of CacheFirst replace the strategy name.

Step 3:

  • now all the assets were pre-cached to cache.
  • Also it will be working in offline using precached assets and responses.

Tips :

--

--

Partha Sai Guttikonda
Partha Sai Guttikonda

Written by Partha Sai Guttikonda

Engineering Intelligence: ML in Imaging | Full-Stack AI Innovator

No responses yet