📖 Scenario: You are building a simple Svelte app that needs to work offline. To do this, you will register a service worker that can cache files and serve them when the network is unavailable.
🎯 Goal: Create a Svelte component that registers a service worker located at /service-worker.js when the app loads.
📋 What You'll Learn
Create a Svelte component with a script block
Check if the browser supports service workers
Register the service worker from /service-worker.js
Handle successful registration and errors with console messages
💡 Why This Matters
🌍 Real World
Service workers help web apps work offline and load faster by caching resources. This is useful for apps that need to work without internet or improve performance.
💼 Career
Knowing how to register and use service workers is important for frontend developers building progressive web apps (PWAs) and improving user experience.
Progress0 / 4 steps
1
Create the Svelte component skeleton
Create a Svelte component with an empty <script> block and a simple <main> section containing the text Service Worker Demo.
Svelte
Hint
Start by writing the basic Svelte component structure with a <script> block and a <main> tag.
2
Add a variable to check service worker support
Inside the <script> block, create a constant called supportsSW that checks if 'serviceWorker' is a property of navigator.
Svelte
Hint
Use const supportsSW = 'serviceWorker' in navigator; to check support.
3
Register the service worker on component mount
Inside the <script> block, import onMount from 'svelte'. Use onMount to run a function that registers the service worker at /service-worker.js only if supportsSW is true. Log 'Service Worker registered' on success and 'Service Worker registration failed' on error.
Svelte
Hint
Use onMount to run code after the component loads. Register the service worker only if supported.
4
Add a simple message in the UI about service worker status
Below the Service Worker Demo text inside the <main> tag, add a paragraph that says Service Worker is supported if supportsSW is true, otherwise Service Worker is not supported. Use Svelte's curly braces and ternary operator.
Svelte
Hint
Use Svelte's curly braces with a ternary operator inside the <p> tag to show the message.
Practice
(1/5)
1. What is the main purpose of a service worker in a Svelte app?
easy
A. To enable offline support and faster loading by caching files
B. To handle user authentication and sessions
C. To manage component state and props
D. To style components dynamically
Solution
Step 1: Understand service worker role
Service workers run in the background and cache files to allow offline use and faster loading.
Step 2: Differentiate from other app features
User authentication, state management, and styling are handled by other parts of the app, not service workers.
Final Answer:
To enable offline support and faster loading by caching files -> Option A
Quick Check:
Service workers = offline support and caching [OK]
Hint: Service workers cache files for offline use [OK]
Common Mistakes:
Confusing service workers with authentication
Thinking service workers manage UI state
Assuming service workers handle styling
2. Which is the correct way to register a service worker in a Svelte app?
easy
A. navigator.serviceWorker.register('/service-worker.js')
B. serviceWorker.register('/service-worker.js')
C. navigator.registerServiceWorker('/service-worker.js')
D. register.serviceWorker('/service-worker.js')
Solution
Step 1: Recall the correct API
The standard API to register a service worker is navigator.serviceWorker.register().
Step 2: Check method and object names
Only navigator.serviceWorker.register('/service-worker.js') uses the correct object (navigator.serviceWorker) and method (register).
Final Answer:
navigator.serviceWorker.register('/service-worker.js') -> Option A
Quick Check:
Use navigator.serviceWorker.register() [OK]
Hint: Use navigator.serviceWorker.register() to register [OK]
Common Mistakes:
Using wrong method names like registerServiceWorker
Calling register on wrong objects
Missing navigator or serviceWorker in the call
3. What will happen if you try to register a service worker in a browser that does not support it, using this code?
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(() => console.log('Registered'))
.catch(err => console.error('Failed', err));
} else {
console.log('No support');
}
medium
A. Registers the service worker anyway
B. Throws an error because serviceWorker is undefined
C. Logs 'No support' and does not attempt registration
D. Logs 'Registered' even if unsupported
Solution
Step 1: Check the feature detection condition
The code checks if 'serviceWorker' exists in navigator before registering.
Step 2: Understand behavior if unsupported
If unsupported, the else block runs, logging 'No support' and skipping registration.
Final Answer:
Logs 'No support' and does not attempt registration -> Option C