A snack-bar for PWAs that gives the user the option to reload the page on a new version of the web app. If the snackbar is dismissed, the Service Worker will remain in the waiting phase and the new version of the website will not be loaded.
🧱 Material Components for the Web (on top of Material Snackbar).
🧱 Workbox
-
Inside your project directory run
npm install mwc-pwa-reload
-
Import component
-
Inside your app's JavaScript file (ex:
app.js
)import 'mwc-pwa-reload';
OR
-
Add a
<script>
tag in an HTML file (ex:index.html
)<script src="./node_modules/mwc-pwa-reload/dist/index.js"></script>
-
-
<script type="module" src="https://unpkg.com/mwc-pwa-reload"></script>
-
Add this listener to your Service Worker file (ex:
sw.js
)addEventListener('message', event => { if (event.data && event.data.type === 'NEW_VERSION') { skipWaiting(); } });
-
Include the
<mwc-pwa-reload>
element inside your HTML file (ex:index.html
)<mwc-pwa-reload></mwc-pwa-reload>
⚠️ The first time you push your code live the snackbar will not be shown, however it will be shown on every new version after that.
⚠️ In the above example the component will run on default options that are explained below 👇👇
💡 For the full list look at the Material Snackbar Docs
-
swUrl: String
- Local Service Worker JavaScript file url- Default =
'./sw.js'
- Default =
-
swScope: String
- The scope by which Service Worker has been registered- Default =
'/'
- Default =
-
labelText: String
- Snackbar main text- Default =
'A new version is available 💎'
- Default =
-
reloadTextColor: String
- Reload action button color- Default =
'#18ffff'
- Change color also with the CSS variable
--mdc-snackbar-action-color
More here 👉 Material Color Palette
- Default =
-
timeout: String|Number
- Snackbar's timeout until it is dismissed (ms)- Default =
6000
⚠️ Need to be between 4000 and 10000
- Default =
-
onDismiss: Function
- Callback when snackbar has been dismissed after timeout or by clicking on the X button.- Default =
null
- Default =
const mSnackbar = document.querySelector('mwc-pwa-reload');
mSnackbar.swUrl = './service-worker.js';
mSnackbar.swScope = '/';
mSnackbar.labelText = 'Hello there! New version in town!';
mSnackbar.timeout = 8000;
mSnackbar.reloadTextColor = '#d500f9';
You can either configure the component using JavaScript or even by HTML attributes.
<mwc-pwa-reload
sw-url="./service-worker.js"
sw-scope="/"
timeout="8000"
reload-text-color="#d500f9"
></mwc-pwa-reload>
Logging is enabled only when the component has a
dev
attibute like so:
<mwc-pwa-reload dev></mwc-pwa-reload>