Service Worker

The Service Worker controller provides useful methods to facilitate interaction with the service worker lifecycle. It enables you to manually update the service worker and notify users when updates are available, particularly useful when the skipWaiting option is set to false.

This component is essential for:

  • Notifying users about available application updates

  • Providing manual update controls

  • Ensuring users get the latest features without forced reloads

  • Creating a smooth update experience without interrupting user workflow

circle-info

When skipWaiting is enabled, the service worker automatically activates when updated. When disabled, you have more control over when the update is applied, which is useful to avoid interrupting user activities.

Usage

Basic Update Button

<div {{ stimulus_controller('@pwa/service-worker') }}>
    <button
        id="update-btn"
        {{ stimulus_action('@pwa/service-worker', 'update', 'click') }}
        style="display:none;"
    >
        Update Available - Click to Refresh
    </button>
</div>

<script>
    document.addEventListener('pwa--service-worker:update-available', () => {
        document.getElementById('update-btn').style.display = 'block';
    });
</script>

Update Notification Banner

Toast Notification with Countdown

Integration with User Settings

Parameters

None

Actions

update

Triggers the service worker update process. When called:

  1. The new service worker becomes active

  2. The page automatically refreshes to load the updated version

  3. Users immediately see the latest features and fixes

circle-exclamation

Targets

None

Events

pwa--service-worker:update-available

Dispatched when a new version of the service worker is detected and ready to be installed.

No payload

This event is fired only when:

  • A new service worker has finished installing

  • The new service worker is waiting to activate

  • The skipWaiting option is set to false in the service worker configuration

Example usage:

Best Practices

  1. Clear communication: Always inform users that updating will refresh the page

  2. Save user work: If your app has forms or unsaved data, warn users before updating

  3. Provide options: Let users choose to update now or later

  4. Visual feedback: Use prominent but non-intrusive UI elements like banners or toasts

  5. Graceful timing: Consider detecting idle time before prompting for updates

  6. Persistent notification: Keep the update notification visible until user acts on it

Configuration Reference

This component works in conjunction with the service worker configuration. To enable manual updates, ensure skipWaiting is set to false:

For more information on service worker configuration, see the Service Worker Configuration page.

Advanced Example: Update Manager

Here's a complete example of an update manager with user preferences and smart update timing:

Last updated

Was this helpful?