Rozumienie i wykorzystanie pracowników służby w JavaScript do wykonywania zdolności offline
Understanding andd Using Service Workers in JavaScript for Offline Capabilities
Modern web users expect instant, reliebles ever n when network conditions are pour or nonexistent. Service Workers are te cornerstone of this expectation, enabling Progressive Web Apps (PWAs) to work offline, load quickliy on flaky connections, and deliver push notifications. Unlike traditional caching techniques, a Service Worker acts a programmable proxy sitting between thee browser and thee network. It asserpents algoing requests from the page and caste cache cache content, necch fresh date fresh fresh thee nestre, work, infix entfresh work.
Service Workers are a new technology - they have been supported d in major browsers for sereal years - but they remain underutized by my many development teams. When built correctly, they transform a static web app into a contesent, app-like experience. We will walk them complete lifecale, displays caching strategies that suit different content type, and cover commerion APIK APIK Backgroud Sync and Push Notifications. By thend, yowill have production-ready tal for integrating Servicke Servickiyouer.
Co to jest Service Worker?
A Service Worker is a JavaScript file that runs in a separate global scope frem your web page, on it own thread. It has no DOM accords and communicates with your page only through gh 1; incore 1; FLT: 0 memorial 3; incorporate;. Its primary joba is to act a middleman for network requests: the browser can send any request frem temu te service Worker, which then decides how t respond - from thee network, from a cache, or by construcret a ting contrise a contrique, a contrique.
Ponieważ to jest to, co robi, to jest to, co robi.
- - serving cached gews when thee network is unacvailable.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Background data syncing Xi1; Xi1; FLT: 1 Xi3; Xi3; - queuing actions while offline andd sendin them when connectivity returns.
- (1); Xi1; FLT: 0 Xi3; Xi3; Push notifications Xi1; Xi1; FLT: 1 Xi3; Xi3; - receiving messages from a server andd displaying them to the use ever when thee app is nott pen.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Performance optimization Xi1; Xi1; FLT: 1 Xi3; Xi3; - pre-caching critial assets so the app loads instantly on repeat visits.
Service Workers rely on a strict security requirement: they only work undeur HTTPS (or on present 1; or on presents 1; FLT: 1 presents 3; for development). Thii protects users frem man-in-thee-middle attacks thauld tamper with the script.
The Service Worker Lifecycle
A Service Worker progresses thugh a well-definied lifecycle: registration, installation, activation, and then idle / fetch handling. Understanding this lifecycle is essential because it determinates when your cached resources previable andd when old caches are cleaned up.
1. Rejestrowanie
Before any Service Worker logic can un run, your page mustt register the script. Thii is done from your main JavaScript file (usually the page 's entry point). Registration informs the browser of the Service Worker' s location and scope. The scope definites which URL the Service Worker can control; by default is the directory of thee script.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(function(registration) {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch(function(error) {
console.log('Registration failed:', error);
});
}
Jeśli ten skrypt już istnieje, to browser compares thee byte-for-byte content with thee previously installaid version. If it has changed, a new version is installalad in thee background while thee old version continues to control spews.
2. Installation
The Receves 1; Thii it te perfect time to po-cache thee essential files your app neds to work offline: thee app shell, core CSS, JavaScript, and any fallback shows.
const CACHE_NAME = 'my-cache-v1';
const urlsToCache = [
'/',
'/styles/main.css',
'/scripts/main.js',
'/offline.html'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
If any of the files fail to download during presendi1; Xi1; FLT: 5 presendi3; Xi3;, the installation step failes andd thee Service Worker is nott considered installed. This is a safety exiure to ensure you never have a partially cached app.
3. Aktywation
After installation, thee browser waits until all views that were loaded with the old Service Worker are closed. Then it fires the indis1; FLT: 6 contribul 3; Event. This event is typically used to o clean up old caches andt to take control of any gews that were opened before activaton.
self.addEventListener('activate', function(event) {
const cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
Calling Bidu1; Xi1; FLT: 8 Bidu3; Xidu3; inside thee Bidu1; Xiun1; FLT: 9 Bidu3; Xiunduller Takes Control of all pen views without out requiring a reload. This is often used d during development for faster iteration.
4. Fetch Events
Once activated, the Service Worker listens for providens 1; Xi1; FLT: 10 contribute 3; Xi3; events. Each time the browser initiats a request from a controlled page, the Service Worker can contromit it. Inside the fetch event handler you implement your caching strategy of choice.
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
Caching Strategies for Different Scenarios
Choosing thee right caching strategy determinates the balance between resresheness and speed. There is no one-size-fits-all solution; different resources require different approaches.
Cache-First (Cache then Network)
Bess for static assets that rarely change: images, fonts, CSS. The Service Worker checks the cache first; if found, it returns emplivately. If not, it fetches from network andd caches thee response. This strategy produces lightning-fast repeat loads.
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
return response || fetch(event.request).then(function(networkResponse) {
return caches.open(CACHE_NAME).then(function(cache) {
cache.put(event.request, networkResponse.clone());
return networkResponse;
});
});
})
);
});
Network-First (Network wigh Cache Fallback)
Ideal for dynamic content: API endpoints, news feeds. Try the network first; if it failes or is very slow, fall back to the cached version. This ensures users always see the latess data unless they ary offline.
self.addEventListener('fetch', function(event) {
event.respondWith(
fetch(event.request)
.then(function(networkResponse) {
return caches.open(CACHE_NAME).then(function(cache) {
cache.put(event.request, networkResponse.clone());
return networkResponse;
});
})
.catch(function() {
return caches.match(event.request);
})
);
});
Stale-While-Revalidate
Bess for resources that don 't have te instantly fresh: profile avatary, RSS feds. Respond expecately with the cached version, but also fetch an update frem the e network in thee background. Next time the resource is requested, the new cache entry is served.
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open(CACHE_NAME).then(function(cache) {
return cache.match(event.request).then(function(cachedResponse) {
var fetchPromise = fetch(event.request).then(function(networkResponse) {
cache.put(event.request, networkResponse.clone());
return networkResponse;
});
return cachedResponse || fetchPromise;
});
})
);
});
Network-Only andd Cache-Only
For sensitiva data such as user banking details, use ides 1; vir1; FLT: 0 vir3; vir3; Network-Only direction; vir1; FLT: 1 vir3; virdis3; (no caching). For purely offline static content (np., a manual), virdis1; FLT: 2 virdis3; Cache-Only direc1; vis1; FLT: 3 virdis3; may bee direcent.
Advanced Service Worker Features
Beyond caching, Service Workers unlock powerful background capabilities.
Sync Background
When a user subjects a form or sends a message while offline, you don 't want to o lose that action. The e meany1; Xion1; FLT: 15 Xion3; Xion3; lets you register a sync event thate browser will fire once connectivity is back.
// In page script
navigator.serviceWorker.ready.then(function(registration) {
return registration.sync.register('sync-messages');
});
// In Service Worker
self.addEventListener('sync', function(event) {
if (event.tag === 'sync-messages') {
event.waitUntil(sendPendingMessages());
}
});
Background Sync is ideal for chat applications, form submissions, or any data queue that needs eventual considency.
Powiadomienia w języku pushskim
Push messages arrive from a server and wake up te Service Worker, which then displays a notification. Thi works even when your web app is closed, giving PWAs a native feel.
self.addEventListener('push', function(event) {
const options = {
body: 'This notification was triggered by a push message.',
icon: '/icons/icon-192x192.png',
badge: '/icons/badge.png',
data: {
url: '/new-content'
}
};
event.waitUntil(
self.registration.showNotification('New Update', options)
);
});
Clicking the notification can open a specific URL using the indi.1; Veld1; FLT: 18 contribution 3; Veld3; event.
Security andScope
Service Workers can contromit t and modify requests, so they mutt be served over HTTPS to prevent malicious scripts frem being injectod. During local development, browsers allow Service Workers on prevent 1; FLT: 19 control3; as an exception. In production, always server Service Worker file over HTTPS.
Thee envice 1; Xi1; FLT: 0 is 3; Xi3; Scope environ1; Xi1; FLT: 1 is 3; Xi3; of a Service Worker determinates which spees it controls. By default, the scope the directory the the directory where the Service Worker script is located. To wideun thee specode (e.g., control all spects undear 1; FLT: 20 Pertion durang registration. You mutt so included a 1; Yu Mutt include a; 1; FLT: 22; FLT: 21; FLT: 1 XAM heder; XP headed; XT: 21; XP headed; XT headed; Tf you extend; extend; Th; extend 's.
Debugging Service Workers
Browser DevTools are essential for inspecting Service Worker behavour. In Chrome, open present 1; Open 1; FLT: 23 context 3; Orange 3; or go to Application → Service Workers. You can see thee status of each worker, manually start / stop them, and clear registrations. Firefox offers similar tools undeer about: debugging.
Wydrukowane znaczniki:
- Xi1; Xi1; FLT: 0 XI3; XI3; Update on reload Xi1; XI1; FLT: 1 XI3; XI3; - in Chrome DevTools, check Xionquent; Update on reload XIQuent; so that a new Service Worker is installalod each time thee page reloads (useful during development).
- (Dz.U. L 311 z 15.11.2014, s. 1).
- (Dz.U. L 311 z 15.11.2014, s. 1).
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Logging Xi1; Xi1; FLT: 1 Xi3; Xi3; - use Xi1; Xi1; FLT: 24 Xi3; Xi3; inside the Service Worker; messages appear in the back ground console e n DevTools.
Wykonanie Implikations
Service Workers can dramatically improwize perceived performance, but they also introdule complex. Pre-caching too man resources during installation can delay the engine; install conformance; step and cause the installation to fail if timeouts occur. A good prace is to cache only the minimal shell in eng1; eng1; FLT: 25 exer3; exer3d lazily cache additional resources during fetcevents.
Cache size is limited per origin (typically a few hundred megabajtes on mobile browsers). Repeatedly caching large media files can fill this quota. Usie te Store API (environ1; environ1; FLT: 26 environ3; environ3;) to monitor usage.
Another performance trap: if your Service Worker performs heavy weight computation inside thee eng1; Ig1; FLT: 27 performance 3; Ig3; handler, it can block or delay network responses. Keep fetch handlers lightweight and use asynchronous Patterns.
Common Pitfalls andHow to Avoid Them
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Serving stale content Xi1; Xi1; FLT: 1 Xi3; Xi3; - always version your caches (np., Xi1; Xi1; FLT: 28 XI3; Xi3;, Xi1; FLT: 29 Xi3; Xi3;) and delete old caches during the Xion1; XiN1; FLT: 30 XIN3; Event. Never usie an unbounded cache name.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Uncached fallback page Xi1; Xi1; FLT: 1 Xi3; Xi3; - if your offline page is not pre-cached, users will see a browser error page. Cache a simply offline fallback during installation.
- W przypadku gdy nie ma możliwości, aby w przypadku gdy w danym przypadku nie ma możliwości, aby w danym przypadku nie było to możliwe, należy podać nazwę "FLT".
- Xi1; Xi1; FLT: 0 XI3; XI3; XI3; XI1; FLT: 32 XI3; XI3; XI1; FLT: 1 XI3; XI3; - if you don 't call XI1; XI1; FLT: 33 XI3; XI3;, the browser will try to fetch the resource on its own, potentially bypassing your caching logic.
Badanie Real-Worlds: A Simple Offline-Ready PWA
Nie ma nic wspólnego z tym, że We 'll stworzył small PWA to kaczki to Shell i provides an offline fallback. Te ukończyły Service Worker file (Behind 1; FLT: 34 Behind 3; Behind 3;):
const CACHE_NAME = 'pwa-shell-v2';
const SHELL_URLS = [
'/',
'/index.html',
'/styles.css',
'/app.js',
'/offline.html'
];
// Install: pre‑cache shell
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
return cache.addAll(SHELL_URLS);
})
);
});
// Activate: clean old caches
self.addEventListener('activate', function(event) {
const cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(name) {
if (!cacheWhitelist.includes(name)) {
return caches.delete(name);
}
})
);
}).then(function() {
return self.clients.claim();
})
);
});
// Fetch: network‑first for pages, cache‑first for static assets
self.addEventListener('fetch', function(event) {
if (event.request.mode === 'navigate') {
// Pages: try network, fall back to cache
event.respondWith(
fetch(event.request).then(function(networkResponse) {
// Update cache with fresh page
const responseClone = networkResponse.clone();
caches.open(CACHE_NAME).then(function(cache) {
cache.put(event.request, responseClone);
});
return networkResponse;
}).catch(function() {
return caches.match(event.request).then(function(cached) {
// If page not cached, show offline fallback
return cached || caches.match('/offline.html');
});
})
);
} else {
// Static assets: cache‑first
event.respondWith(
caches.match(event.request).then(function(cached) {
return cached || fetch(event.request).then(function(networkResponse) {
caches.open(CACHE_NAME).then(function(cache) {
cache.put(event.request, networkResponse.clone());
});
return networkResponse;
});
})
);
}
});
This example use a network-first approach for navigation (fresh gews when online, offline fallback when not) and cache-first for all tequet assets. The code handle cache versioning street.
Konkluzja
Service Workers are te backbone of modern offline-capable web applications. They provide a programmable network layer that goes far beyond simple caching: background sync, push notifications, and full control over how resources are served. By understand the e lifecycle, choosing the right caching strategy for each resource type, and afareing security best practives, you can build web experiveres that are, fact, and end assinging.
To dive deeper into the API, consult the official documentation on indi1; indi1; FLT: 0 div3; IB3; MDN XI1; IB3; IB3; IB3; IBL; IBL; IBL: IBL: 2 IBL; IBL: 3; IBL: IBL: IBL; IBL: IBL; IBD: IBD; IBD: IBL; IBL: IBD: IBL; IBL: IBL: IBL: IBL: IBL: IBL: IF: IBD; IBL: IBL; IBL: IBL; IBL: IBL; IBL: IF: IBD; IBD: IF; IBL; IF: IF: IF: IF: IBL: IBL: IBL: IBL: IBL: IB@@