PWA Service Worker

When the @PWA annotation is found, Vaadin automatically generates a simple service worker during application startup.

The generated service worker:

  • Caches offline resources, including the offline fallback page, icons, and custom (user-defined) offline resources.

  • Handles simple offline navigation by serving the offline page.

Note
The service worker can only respond to full navigation events, like refresh or direct navigation to a URL.

The service worker uses Google Workbox to cache resources. The necessary Workbox files are stored in the VAADIN/resources/workbox/ folder.

Defining Custom Cache Resources

You can define custom resources to be cached automatically by the service worker, using the offlineResources parameter in the @PWA annotation.

Example: Defining styles/offline.css, img/offline.jpg and js/jquery.js as cacheable offline resources.

Java

  1. @PWA(name = "My Progressive Web Application",
  2. shortName = "MyPWA",
  3. offlineResources = { "styles/offline.css",
  4. "js/jquery.js", "img/offline.jpg" })

Overriding the Generated Service Worker

You can override the generated service worker with a custom service worker.

To override the generated service worker file:

  1. Create a custom service worker file and name it sw.js.

  2. Add the file to your src/main/webapp/ folder.

Note
To ensure that your custom service worker deals with offline support and resource caching properly, you can copy the default service worker from browser resources and use it as a template.