Precache assets using wordbox
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)
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
Step 1:
- we will config pwa inside vue.config.js
- In this step we will select the workboxPluginMode →InjectManifest
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:
- Run your project for prod using →npm run build
- new dir will be generated →dist folder
- run a live http server with (https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb?hl=en-GB&utm_source=chrome-ntp-launcher)
- now all the assets were pre-cached to cache.
- Also it will be working in offline using precached assets and responses.
Tips :
- We can https://realfavicongenerator.net/ for generating all types of icons, images, and favicons for PWA. Usage.