How can I register a service-worker to cache essential assets offline?
Asked on Oct 10, 2025
Answer
Registering a service worker to cache essential assets offline is a key strategy for improving web performance and reliability. This involves creating a service worker script that listens for the "install" event to cache necessary files.
<!-- BEGIN COPY / PASTE -->
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
console.log('Service Worker registered with scope:', registration.scope);
}, function(error) {
console.log('Service Worker registration failed:', error);
});
});
}
<!-- END COPY / PASTE -->Additional Comment:
- Create a "service-worker.js" file in your root directory.
- In the service worker script, listen for the "install" event to cache essential assets using the Cache API.
- Ensure the service worker is registered after the page load event to avoid blocking the initial rendering.
- Test the service worker in a controlled environment before deploying it to production.
Recommended Links: