Top Related Projects
📦 Workbox: JavaScript libraries for Progressive Web Apps
It's online. It's offline. It's a Service Worker!
✈️ Easily create sites that work offline as well as online
[Deprecated] A collection of service worker tools for offlining runtime requests
Quick Overview
The w3c/ServiceWorker repository is the official specification for the Service Worker API, maintained by the World Wide Web Consortium (W3C). Service Workers are a key technology for building Progressive Web Apps (PWAs), enabling offline functionality, background sync, and push notifications for web applications.
Pros
- Enables offline functionality for web applications
- Improves performance through caching and background processing
- Allows for push notifications in web apps
- Enhances the overall user experience of web applications
Cons
- Can be complex to implement and debug
- Requires HTTPS for security reasons, which may be challenging for some developers
- May cause issues with caching if not implemented correctly
- Limited browser support in older versions
Code Examples
- Registering a Service Worker:
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);
});
}
- Caching resources in the install event:
self.addEventListener('install', event => {
event.waitUntil(
caches.open('my-cache-v1').then(cache => {
return cache.addAll([
'/',
'/styles/main.css',
'/scripts/app.js',
'/images/logo.png'
]);
})
);
});
- Intercepting fetch events and serving cached resources:
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
});
Getting Started
To get started with Service Workers:
- Create a
sw.js
file in your project's root directory. - Add the registration code to your main JavaScript file:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}
- Implement the
install
,activate
, andfetch
event listeners in yoursw.js
file to handle caching and serving resources. - Ensure your web server is configured to serve over HTTPS.
- Test your Service Worker implementation using browser developer tools.
Competitor Comparisons
📦 Workbox: JavaScript libraries for Progressive Web Apps
Pros of Workbox
- Higher-level abstraction, simplifying service worker implementation
- Rich set of pre-built strategies for caching and routing
- Extensive documentation and examples for various use cases
Cons of Workbox
- Adds additional dependency and bundle size to projects
- May introduce unnecessary complexity for simple service worker needs
- Less flexibility for custom, low-level service worker implementations
Code Comparison
ServiceWorker (basic caching):
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
Workbox (equivalent caching):
import { registerRoute } from 'workbox-routing';
import { CacheFirst } from 'workbox-strategies';
registerRoute(
({ request }) => request.destination === 'image',
new CacheFirst()
);
The ServiceWorker repository focuses on the core specification and implementation of service workers, while Workbox provides a higher-level toolkit built on top of service workers. ServiceWorker offers more granular control but requires more manual implementation, whereas Workbox simplifies common tasks at the cost of some flexibility and additional overhead.
It's online. It's offline. It's a Service Worker!
Pros of serviceworker-cookbook
- Provides practical examples and recipes for implementing Service Workers
- Offers a more user-friendly approach for developers learning Service Workers
- Includes a variety of use cases and scenarios for different Service Worker implementations
Cons of serviceworker-cookbook
- May not always reflect the most up-to-date Service Worker specifications
- Focuses more on practical implementation rather than the underlying standard
- Could potentially lead to outdated practices if not regularly maintained
Code Comparison
ServiceWorker (specification):
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
serviceworker-cookbook (example recipe):
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open('mysite-dynamic').then(function(cache) {
return cache.match(event.request).then(function(response) {
return response || fetch(event.request).then(function(response) {
cache.put(event.request, response.clone());
return response;
});
});
})
);
});
The ServiceWorker repository focuses on the core specification, while the serviceworker-cookbook provides more detailed, practical implementations with additional features like dynamic caching.
✈️ Easily create sites that work offline as well as online
Pros of UpUp
- Simplified API for creating offline-first web applications
- Easy to integrate into existing projects with minimal setup
- Provides a higher-level abstraction for common offline functionality
Cons of UpUp
- Limited flexibility compared to the more comprehensive ServiceWorker API
- May not support advanced use cases or complex caching strategies
- Smaller community and fewer resources compared to the W3C standard
Code Comparison
UpUp:
UpUp.start({
'content-url': 'offline.html',
'assets': ['img/logo.png', 'css/style.css']
});
ServiceWorker:
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
UpUp provides a more concise and user-friendly API for basic offline functionality, while ServiceWorker offers greater control and flexibility for advanced caching and offline strategies. UpUp is better suited for quick implementation in smaller projects, whereas ServiceWorker is ideal for larger applications requiring fine-grained control over offline behavior and caching mechanisms.
[Deprecated] A collection of service worker tools for offlining runtime requests
Pros of sw-toolbox
- Simplified API for common service worker caching strategies
- Pre-built routing and caching patterns for easier implementation
- Smaller learning curve for developers new to service workers
Cons of sw-toolbox
- Less flexibility compared to raw ServiceWorker implementation
- May not cover all advanced use cases or custom requirements
- Dependency on an external library instead of native browser APIs
Code Comparison
ServiceWorker (basic caching):
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
sw-toolbox (basic caching):
importScripts('sw-toolbox.js');
toolbox.router.get('/*', toolbox.cacheFirst);
Summary
ServiceWorker provides a low-level API for implementing service workers, offering maximum flexibility and control. It's ideal for complex use cases and custom implementations but requires more in-depth knowledge and code.
sw-toolbox simplifies service worker implementation with pre-built patterns and a higher-level API. It's great for quick setups and common use cases but may limit advanced customization.
Choose ServiceWorker for full control and custom requirements, or sw-toolbox for faster development and simpler implementation of common caching strategies.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Whatâs going on here?
Service workers are a new browser feature that provide event-driven scripts that run independently of web pages. Unlike other workers, service workers can be shut down at the end of events, note the lack of retained references from documents, and they have access to domain-wide events such as network fetches.
Service workers also have scriptable caches. Along with the ability to respond to network requests from certain web pages via script, this provides a way for applications to âgo offlineâ.
Service workers are meant to replace the (oft maligned) HTML5 Application Cache. Unlike AppCache, service workers are comprised of scriptable primitives with an extensive use of Promises that make it possible for application developers to build URL-friendly, always-available applications in a sane and layered way.
To understand the design and how you might build apps with service workers, see the explainer document.
Spec and API development
For the nitty-gritty of the API, the draft W3C specifications are authoritative. Service Workers Nightly is a living document. Service Workers 1 is a subset of the nightly version that is advancing toward a W3C Recommendation. For implementers and developers who seek all the latest features, Service Workers Nightly is a right document that is constantly reflecting new requirements. For version 1, contributors plan to focus on fixing bugs and resolving compatibility issues without including new features from the nightly version.
Spec development happens via issues in this repository. For general discussion, please use the public-webapps@w3.org mailing list with a Subject:
prefix of [service-workers]
.
Updates to the spec must reference resolved issues marked needs spec
.
To make edits to the design, please send pull requests against the Nightly spec on the master branch. We use bikeshed. So, change docs/index.bs
and submit it with the corresponding bikesheded index.html
.
Examples
The W3C Web Mobile Group have defined a series of use-cases where service worker is particularly useful. You can help by adding more use cases, draft implementation code, or even working examples once browsers support the required APIs.
About labels and milestones on issues
This is to explain how we use labels and milestones to triage the issues. Note: This is a draft, suggestions for improvements are welcomed.
Prioritization
- enhancement: is for anything that was assessed as not having any impact on the decisions for the current milestone and can therefore be safely discussed, rejected or prioritized later.
- milestone: is used to mark issues we agreed to get done in principle by a given revision. For the sake of efficiency, we tend to only focus on the current milestone and leave everything else without specific milestones.
- impacts MVP: is used to mark issues impacting the âMinimal Viable Productâ. The MVP is the minimal scope of API that can solve actual use cases. These issues have the highest priority.
Risk labels for impacts MVP issues
- medium risk: to further refine the âimpacts MVPâ issues. It indicates that the issue is moderately complex and that reaching a conclusion might take some time. These are of higher priority than issues with no risk label but are of lower priority than issues with a âhigh riskâ label.
- high risk: to further refine the âimpacts MVPâ issues. It indicates that the issue is significantly complex and that reaching a conclusion might take a lot of time and effort. These are of higher priority than issues with no risk label or a âmedium riskâ label.
Actions
- needs spec: a decision has been made and the spec needs to be updated.
- spec detail: has no significant implications for implementers nor web developers.
- decided: to record that a decision has been made.
- invalid: when something doesnât constitute a valid issue.
- wontfix: a decision has been made not to pursue this issue further.
- duplicate: when a similar issue has already been filed.
- bug: an oversight that needs to be fixed.
Areas
- fetch: relates to Fetch
- lifecycle: relates to lifecycle aspects of service worker
- cache: relevant to the Cache APIs
- question: not an actual issue. Items that have been filed in order to gain a better understanding of service worker.
Top Related Projects
📦 Workbox: JavaScript libraries for Progressive Web Apps
It's online. It's offline. It's a Service Worker!
✈️ Easily create sites that work offline as well as online
[Deprecated] A collection of service worker tools for offlining runtime requests
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot