0
0
Svelteframework~5 mins

Service workers in Svelte

Choose your learning style9 modes available
Introduction

Service workers help your web app work offline and load faster by managing network requests in the background.

You want your app to work even without internet connection.
You want to cache files so your app loads quickly on repeat visits.
You want to show notifications or sync data in the background.
You want to improve user experience by handling slow or unreliable networks.
Syntax
Svelte
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js')
      .then(registration => {
        console.log('Service Worker registered with scope:', registration.scope);
      })
      .catch(error => {
        console.log('Service Worker registration failed:', error);
      });
  });
}

This code checks if the browser supports service workers before registering one.

The service worker file (service-worker.js) controls caching and background tasks.

Examples
Simple registration of a service worker file named sw.js.
Svelte
navigator.serviceWorker.register('/sw.js');
Registers a service worker with a specific scope, controlling only URLs under /app/.
Svelte
navigator.serviceWorker.register('/sw.js', { scope: '/app/' });
Waits until the service worker is active and ready to control pages.
Svelte
navigator.serviceWorker.ready.then(registration => {
  console.log('Service Worker is active:', registration);
});
Sample Program

This Svelte component registers a service worker when the component mounts. It logs success or failure in the browser console.

Svelte
<script>
  import { onMount } from 'svelte';

  onMount(() => {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/service-worker.js')
        .then(registration => {
          console.log(`Service Worker registered with scope: ${registration.scope}`);
        })
        .catch(error => {
          console.log('Service Worker registration failed:', error);
        });
    } else {
      console.log('Service Workers are not supported in this browser.');
    }
  });
</script>

<main>
  <h1>Service Worker Demo</h1>
  <p>Check the console to see the registration status.</p>
</main>
OutputSuccess
Important Notes

Service workers must be served over HTTPS except on localhost for testing.

Service workers run separately from your web page and can intercept network requests.

Remember to update your service worker file carefully to avoid caching issues.

Summary

Service workers let your app work offline and load faster by caching files.

Register service workers in your Svelte app using navigator.serviceWorker.register().

Check browser support before registering to avoid errors.