Consider this Svelte code snippet that registers a service worker:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(() => console.log('Service Worker registered'))
.catch(err => console.error('Registration failed:', err));
}What is the expected behavior when this code runs in a supported browser?
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js') .then(() => console.log('Service Worker registered')) .catch(err => console.error('Registration failed:', err)); }
Think about what navigator.serviceWorker.register does and how promises work.
The code checks if service workers are supported, then attempts to register the script at '/sw.js'. It logs success or failure messages based on the promise outcome. Activation and control happen later, not immediately.
navigator.serviceWorker.controller after page load if no service worker was previously controlling the page?After registering a service worker for the first time and reloading the page, what will navigator.serviceWorker.controller be on the first load?
console.log(navigator.serviceWorker.controller);
Think about when a service worker starts controlling a page.
On the first load after registration, the service worker is installed but not yet controlling the page, so navigator.serviceWorker.controller is null. It controls pages only after reload.
Examine this service worker code snippet:
self.addEventListener('install', event => {
event.waitUntil(
caches.open('v1').then(cache => {
cache.addAll([
'/index.html',
'/styles.css',
'/script.js'
]);
})
);
});Why might the caching fail silently?
self.addEventListener('install', event => { event.waitUntil( caches.open('v1').then(cache => { return cache.addAll([ '/index.html', '/styles.css', '/script.js' ]); }) ); });
Check how promises are handled inside event.waitUntil.
The cache.addAll method returns a promise, but it is not returned from the then callback. This means event.waitUntil does not wait for caching to finish, so the install event may complete early, causing caching to fail silently.
In service worker lifecycle, what is the primary role of the 'activate' event?
Think about what happens after installation but before the service worker controls pages.
The 'activate' event is used to remove old caches and claim control over pages so the new service worker can start handling fetch events.
In SvelteKit, you want to register a service worker only on the client side inside a +layout.svelte component. Which code snippet correctly does this?
Remember that navigator is only available in the browser and onMount runs only on client side.
Option A correctly uses onMount to run code only on the client, and checks for service worker support before registering. Option A runs code immediately, which may cause errors during server-side rendering. Option A accesses navigator outside onMount, causing errors. Option A does not check for service worker support.