Blog>
Snippets

Offline Capabilities with Vue 3 and Service Workers

Setup a service worker with Vue 3 to cache assets for offline use, showing how to integrate it with a Vue application for enhanced mobile experiences.
import { createApp } from 'vue';
import App from './App.vue';

// Check that service workers are supported
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js').then(registration => {
      console.log('SW registered: ', registration);
    }).catch(registrationError => {
      console.log('SW registration failed: ', registrationError);
    });
  });
}

const app = createApp(App);
//... further initialization and app mounting
app.mount('#app');
This code snippet registers the service worker when the Vue app loads. It checks if the browser supports service workers, and if so, registers the service worker from a file named service-worker.js.
// service-worker.js
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open('v1').then((cache) => {
      return cache.addAll([
        '/index.html',
        '/css/style.css',
        '/js/script.js'
        //... add other assets and pages you want to cache
      ]);
    })
  );
});

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => {
      return response || fetch(event.request);
    })
  );
});
This is the service worker file (service-worker.js) itself. It has two event listeners, one for the 'install' event to cache necessary assets, and one for the 'fetch' event to serve cached assets when offline or to fetch from the network when online.
import { onMounted } from 'vue';

export default {
  setup() {
    onMounted(() => {
      if (!navigator.onLine) {
        console.log('The app is currently offline!');
      }
    });

    // define more component logic
  }
};
This Vue component snippet demonstrates how to use the Vue Composition API lifecycle hook `onMounted` to detect if the app is offline when the component is mounted, and log a message to the console if that's the case.