Top Related Projects
A repo containing samples tied to new functionality in each release of Google Chrome.
Service Workers
✈️ Easily create sites that work offline as well as online
[Deprecated] A collection of service worker tools for offlining runtime requests
Quick Overview
The mdn/serviceworker-cookbook is a collection of working examples demonstrating how to use Service Workers in web applications. It provides practical implementations of various Service Worker features, helping developers understand and implement offline functionality, push notifications, and other progressive web app capabilities.
Pros
- Comprehensive collection of Service Worker examples
- Well-documented and easy to understand implementations
- Maintained by Mozilla Developer Network (MDN), ensuring reliability and up-to-date information
- Covers a wide range of Service Worker use cases
Cons
- Some examples may become outdated as browser implementations evolve
- Limited to Service Worker functionality, not covering other aspects of Progressive Web Apps
- May require additional research for more complex real-world scenarios
Code Examples
- Basic Service Worker Registration:
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);
});
}
This code checks if the browser supports Service Workers and registers a Service Worker file (sw.js) if supported.
- Caching Assets 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'
]);
})
);
});
This example shows how to cache assets during the Service Worker installation phase.
- Intercepting Fetch Events:
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
});
This code intercepts fetch events and attempts to serve cached responses before making network requests.
Getting Started
To get started with the Service Worker Cookbook:
-
Clone the repository:
git clone https://github.com/mdn/serviceworker-cookbook.git
-
Navigate to the project directory:
cd serviceworker-cookbook
-
Install dependencies:
npm install
-
Start the local server:
npm start
-
Open your browser and visit
http://localhost:3000
to explore the examples.
Competitor Comparisons
A repo containing samples tied to new functionality in each release of Google Chrome.
Pros of samples
- Broader scope, covering various Chrome and web platform features beyond just Service Workers
- More frequently updated with newer examples and technologies
- Larger community and more contributors, potentially leading to higher-quality examples
Cons of samples
- Less focused on Service Workers specifically, making it harder to find relevant examples
- May include experimental or less stable features, which could be confusing for beginners
- Examples might be more complex or less beginner-friendly compared to serviceworker-cookbook
Code Comparison
serviceworker-cookbook example (basic caching):
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
samples example (using Workbox for caching):
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js');
workbox.routing.registerRoute(
({request}) => request.destination === 'image',
new workbox.strategies.CacheFirst()
);
Both repositories provide valuable resources for web developers, with serviceworker-cookbook focusing specifically on Service Workers and samples offering a wider range of Chrome and web platform features. The choice between them depends on the developer's needs and level of expertise.
Service Workers
Pros of ServiceWorker
- Official W3C specification repository, providing the most up-to-date and authoritative information
- Contains detailed documentation on the Service Worker API, including edge cases and implementation details
- Includes test suites and conformance requirements for browser vendors
Cons of ServiceWorker
- Primarily focused on the specification, not practical implementation examples
- May be more challenging for beginners to understand and apply directly
- Less emphasis on real-world use cases and patterns
Code Comparison
ServiceWorker (specification example):
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
serviceworker-cookbook (practical example):
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 defining the API, while serviceworker-cookbook provides more practical, real-world examples with additional features like dynamic caching.
✈️ Easily create sites that work offline as well as online
Pros of UpUp
- Simpler and more focused API, making it easier for beginners to implement offline functionality
- Provides a higher-level abstraction for common offline use cases
- Smaller codebase, resulting in a lighter-weight solution
Cons of UpUp
- Less flexible than serviceworker-cookbook for complex offline scenarios
- Fewer examples and recipes compared to the comprehensive serviceworker-cookbook
- Limited to basic offline page and content caching functionality
Code Comparison
UpUp:
UpUp.start({
'content-url': 'offline.html',
'assets': ['img/logo.png', 'css/style.css']
});
serviceworker-cookbook:
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
The UpUp example shows a simple setup for offline content, while the serviceworker-cookbook example demonstrates a more flexible approach to handling fetch events and caching.
[Deprecated] A collection of service worker tools for offlining runtime requests
Pros of sw-toolbox
- More focused on providing a set of tools and utilities for service worker development
- Offers a higher-level abstraction for common service worker tasks
- Maintained by Google, potentially benefiting from their expertise in web technologies
Cons of sw-toolbox
- Less comprehensive in terms of examples and use cases
- Not actively maintained (last commit was in 2018)
- May have a steeper learning curve for beginners due to its abstraction layer
Code Comparison
serviceworker-cookbook example:
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
sw-toolbox example:
importScripts('sw-toolbox.js');
toolbox.router.get('/*', toolbox.networkFirst, {
networkTimeoutSeconds: 5
});
The serviceworker-cookbook example shows a more basic approach to handling fetch events, while sw-toolbox provides a higher-level API for routing and caching strategies. The sw-toolbox code is more concise but may require additional understanding of the library's concepts.
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
ServiceWorker Cookbook
It's online. It's offline. It's a Service Worker!
Service workers are a new technology to aid developers in:
- creating realistic, reliable offline experiences
- vastly improving performance when online
- logically and dynamically caching files for any purpose
The ServiceWorker API, which has recently made its way into Firefox Developer Edition, will change the way web and mobile app developers make their websites fast and functional!
What is in this cookbook?
This cookbook contains dozens of practical, detailed, and working examples of service worker usage. These examples are for developers from beginner to expert and illustrate a number of APIs:
How to contribute
We are always happy to accept contributions! You can follow the process below to start creating a new recipe:
- Clone this repository
- Execute
cd serviceworker-cookbook && npm install
- Copy the
_recipe_template
directory, rename it, and add all recipe code and resources within that new directory - Execute
gulp watch
to start the server - Navigate to http://localhost:3000 to develop and test your recipe
When it's all done, please submit a pull request to the ServiceWorker Cookbook.
Similar projects & prior art
- Google Chrome Service Worker Samples
- Is ServiceWorker Ready?
- Embrace The Network
- The Offline Cookbook
Attributions
MealKeeper Icon by Shlyapnikova, Creative Commons (Attribution 3.0 Unported)
Attribution of pictures in Caching strategies category can be found at lorempixel.com.
Top Related Projects
A repo containing samples tied to new functionality in each release of Google Chrome.
Service Workers
✈️ 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