Utilizing Service Workers for Offline Capabilities in JavaScript Applications
Guidelines on implementing service workers to enable offline functionality and improve performance in JavaScript applications.
0 likes
185 views
Rule Content
---
description: Enforce best practices for implementing service workers to enable offline functionality and improve performance in JavaScript applications.
globs: ["**/*.js"]
tags: [service-workers, offline-capabilities, performance]
priority: 2
version: 1.0.0
---
# Utilizing Service Workers for Offline Capabilities in JavaScript Applications
## Context
- Applicable to JavaScript projects aiming to implement service workers for offline functionality and performance enhancements.
- Assumes familiarity with JavaScript and web development concepts.
## Requirements
- **Scope Definition**: Place the service worker file at the root directory to control the entire site, or explicitly define its scope during registration.
- **Registration Timing**: Register the service worker after the `load` event to avoid competing with page load resources.
- **Cache Versioning**: Use unique identifiers for each cache version to manage updates and prevent conflicts.
- **Progressive Enhancement**: Ensure the application functions correctly without the service worker for browsers that do not support it.
## Examples
<example>
// Registering service worker after page load
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js', { scope: '/' })
.then(registration => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch(error => {
console.error('Service Worker registration failed:', error);
});
});
}
</example>
<example type="invalid">
// Registering service worker before page load
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch(error => {
console.error('Service Worker registration failed:', error);
});
}
</example>