The Service Worker File Structure
What you'll learn: How to create and organize your service worker file and why it runs independently from your main application.
Now that you've registered a service worker, you need to understand what goes inside that file and how it operates differently from regular JavaScript.
A Separate Execution Context
Your service worker lives in its own JavaScript file (commonly sw.js or service-worker.js) and runs in a completely separate thread from your main page. Think of it like a backstage crew at a theater—while the actors (your web page) perform on stage, the crew works behind the scenes handling props and lighting, independent of what's happening on stage.
This separation means:
- Service workers have no direct access to the DOM
- They can't use
windowordocumentobjects - They communicate with pages through messages
- They persist even when your pages are closed
Basic File Structure
Your service worker file contains event listeners that respond to lifecycle events and network requests. At minimum, you'll structure it like this:
// sw.js
// Runs once when service worker installs
self.addEventListener('install', (event) => {
console.log('Service Worker installing');
});
// Runs when service worker activates
self.addEventListener('activate', (event) => {
console.log('Service Worker activating');
});
// Intercepts network requests
self.addEventListener('fetch', (event) => {
console.log('Fetching:', event.request.url);
});
Note the use of self instead of window—this refers to the service worker's global scope.
Why This Structure Matters
Because service workers operate independently, they can work even when no pages are open, enabling features like background sync and push notifications. This architecture is what makes true offline functionality possible.
Key Takeaway: Service workers run in a separate file with their own execution context, using event listeners to respond to lifecycle events and network requests without direct DOM access.