sw-toolbox
[Deprecated] A collection of service worker tools for offlining runtime requests
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
https://github.com/facebookincubator/create-react-app + Progressive Web App goodness
Webpack plugin that generates a service worker using sw-precache that will cache webpack's bundles' emitted assets. You can optionally pass sw-precache configuration options to webpack through this plugin.
Offline plugin (ServiceWorker, AppCache) for webpack (https://webpack.js.org/)
Quick Overview
sw-toolbox is a collection of tools for service worker developers, providing a set of common caching strategies and utilities. It simplifies the process of creating and managing service workers for web applications, enhancing offline capabilities and performance.
Pros
- Easy-to-use API for implementing common caching strategies
- Lightweight and modular design
- Improves web application performance and offline functionality
- Well-documented with clear examples
Cons
- No longer actively maintained (last update in 2018)
- Limited to older service worker specifications
- May lack support for newer browser features
- Potential compatibility issues with modern web development practices
Code Examples
- Basic usage of sw-toolbox:
importScripts('sw-toolbox.js');
toolbox.router.get('/(.*)', toolbox.networkFirst, {
networkTimeoutSeconds: 5
});
This code imports sw-toolbox and sets up a route that uses the "network first" strategy with a 5-second timeout.
- Caching static assets:
toolbox.router.get('/static/(.*)', toolbox.cacheFirst);
This example caches static assets using the "cache first" strategy.
- Custom caching strategy:
toolbox.router.get('/api/(.*)', function(request, values, options) {
return fetch(request)
.then(function(response) {
if (response.status === 200) {
toolbox.cacheOnly.put(request, response.clone());
}
return response;
});
});
This code implements a custom caching strategy for API requests, caching successful responses for future use.
Getting Started
To use sw-toolbox in your project:
-
Install via npm:
npm install sw-toolbox
-
In your service worker file (e.g.,
sw.js
):importScripts('node_modules/sw-toolbox/sw-toolbox.js'); toolbox.router.get('/*', toolbox.networkFirst); toolbox.router.get('/images/*', toolbox.cacheFirst); self.addEventListener('install', function(event) { event.waitUntil(toolbox.precache([ '/index.html', '/styles/main.css', '/script/main.js' ])); });
-
Register the service worker in your main JavaScript file:
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js'); }
Note: As sw-toolbox is no longer maintained, consider using more modern alternatives like Workbox for new projects.
Competitor Comparisons
📦 Workbox: JavaScript libraries for Progressive Web Apps
Pros of Workbox
- More comprehensive and feature-rich, offering a wider range of caching strategies and tools
- Actively maintained and regularly updated, with better documentation and community support
- Modular architecture allows for more flexible and customizable implementations
Cons of Workbox
- Steeper learning curve due to its more complex API and extensive features
- Larger bundle size, which may impact performance for smaller applications
- Requires more configuration and setup compared to sw-toolbox's simpler approach
Code Comparison
sw-toolbox:
toolbox.router.get('/images/*', toolbox.cacheFirst);
toolbox.router.get('/*', toolbox.networkFirst, {
networkTimeoutSeconds: 5
});
Workbox:
workbox.routing.registerRoute(
/\/images\/.*/,
new workbox.strategies.CacheFirst()
);
workbox.routing.registerRoute(
/\/.*/,
new workbox.strategies.NetworkFirst({
networkTimeoutSeconds: 5
})
);
Both examples demonstrate routing and caching strategies, but Workbox offers a more structured and flexible approach with its modular design and strategy classes.
It's online. It's offline. It's a Service Worker!
Pros of serviceworker-cookbook
- Comprehensive collection of Service Worker recipes and examples
- Well-documented with explanations for each recipe
- Regularly updated with new examples and best practices
Cons of serviceworker-cookbook
- Less focused on providing a ready-to-use library
- May require more manual implementation for common use cases
- Steeper learning curve for beginners
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 provides more detailed, customizable examples, while sw-toolbox offers a higher-level abstraction for common caching strategies. sw-toolbox simplifies implementation with pre-built routing and caching methods, making it easier for developers to quickly set up Service Workers. However, serviceworker-cookbook offers a wider range of examples and more flexibility for complex use cases.
✈️ Easily create sites that work offline as well as online
Pros of UpUp
- Simpler and more lightweight, focusing specifically on offline functionality
- Easier to set up and use for basic offline scenarios
- Better documentation and examples for beginners
Cons of UpUp
- Less flexible and feature-rich compared to sw-toolbox
- Limited to offline content serving, lacking advanced caching strategies
- Not actively maintained (last update in 2019)
Code Comparison
UpUp basic setup:
UpUp.start({
'content-url': 'offline.html',
'assets': ['images/logo.png', 'css/style.css', 'js/app.js']
});
sw-toolbox basic setup:
importScripts('sw-toolbox.js');
toolbox.router.get('/*', toolbox.networkFirst, {
networkTimeoutSeconds: 5
});
toolbox.precache(['index.html', 'styles/main.css', 'scripts/main.js']);
Both libraries aim to simplify service worker implementation, but sw-toolbox offers more advanced features and flexibility. UpUp is more suitable for simple offline scenarios, while sw-toolbox provides a wider range of caching strategies and routing options. However, it's worth noting that sw-toolbox is now deprecated in favor of Workbox, which offers even more powerful service worker tools.
https://github.com/facebookincubator/create-react-app + Progressive Web App goodness
Pros of create-react-pwa
- Specifically tailored for React applications, providing a streamlined setup for React-based PWAs
- Includes modern tooling and configurations out of the box, such as Create React App and Workbox
- Offers a more opinionated and complete starting point for PWA development
Cons of create-react-pwa
- Less flexible compared to sw-toolbox, as it's focused on React ecosystems
- May have a steeper learning curve for developers not familiar with React or modern JavaScript tooling
- Limited to the specific PWA features and configurations provided by the template
Code Comparison
sw-toolbox:
toolbox.router.get('/images/*', toolbox.cacheFirst);
toolbox.router.get('/*', toolbox.networkFirst, {
networkTimeoutSeconds: 5
});
create-react-pwa:
workbox.routing.registerRoute(
/\.(?:png|gif|jpg|jpeg|svg)$/,
new workbox.strategies.CacheFirst()
);
workbox.routing.registerRoute(
new RegExp('https://api.example.com/'),
new workbox.strategies.NetworkFirst()
);
Both examples demonstrate routing and caching strategies, but create-react-pwa uses the more modern Workbox library, while sw-toolbox uses its own API. create-react-pwa's approach is more aligned with current best practices for service worker implementation in PWAs.
Webpack plugin that generates a service worker using sw-precache that will cache webpack's bundles' emitted assets. You can optionally pass sw-precache configuration options to webpack through this plugin.
Pros of sw-precache-webpack-plugin
- Seamless integration with Webpack, making it easier to use in Webpack-based projects
- Automatically generates a service worker based on your Webpack build output
- Provides configuration options specific to Webpack environments
Cons of sw-precache-webpack-plugin
- More limited in scope, focusing primarily on precaching assets
- Less flexible for custom caching strategies compared to sw-toolbox
- May require additional setup for advanced service worker features
Code Comparison
sw-toolbox:
toolbox.router.get('/images/*', toolbox.cacheFirst, {
cache: {
name: 'image-cache',
maxEntries: 50
}
});
sw-precache-webpack-plugin:
new SWPrecacheWebpackPlugin({
cacheId: 'my-project-name',
filename: 'service-worker.js',
staticFileGlobs: ['dist/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff}'],
minify: true,
});
sw-toolbox offers more granular control over caching strategies for different routes, while sw-precache-webpack-plugin focuses on precaching assets generated by Webpack. The latter is more tightly integrated with the Webpack ecosystem, making it easier to use in Webpack projects but potentially less flexible for complex service worker configurations.
Offline plugin (ServiceWorker, AppCache) for webpack (https://webpack.js.org/)
Pros of offline-plugin
- Integrates seamlessly with webpack, making it easier to use in modern JavaScript projects
- Provides automatic generation of service worker and AppCache files
- Offers more advanced caching strategies and configuration options out of the box
Cons of offline-plugin
- Requires webpack as a dependency, limiting its use in non-webpack projects
- May have a steeper learning curve for developers unfamiliar with webpack ecosystem
- Less flexible for custom service worker implementations compared to sw-toolbox
Code Comparison
sw-toolbox:
toolbox.router.get('/images/*', toolbox.cacheFirst);
toolbox.router.get('/*', toolbox.networkFirst, {
networkTimeoutSeconds: 5
});
offline-plugin:
new OfflinePlugin({
caches: {
main: [':rest:'],
additional: ['*.chunk.js']
},
ServiceWorker: {
events: true
}
})
Both libraries aim to simplify the process of creating offline-capable web applications, but they approach the task differently. sw-toolbox focuses on providing a simple API for routing and caching strategies, while offline-plugin integrates directly with webpack and offers more automated configuration options. The choice between the two depends on the project's build setup, developer preferences, and specific offline requirements.
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
â ï¸ sw-toolbox â ï¸
sw-toolbox
and sw-precache
are deprecated in favor of Workbox.
Please read this migration guide
for information on upgrading.
About
A collection of tools for service workers
Service Worker Toolbox provides some simple helpers for use in creating your own service workers. Specifically, it provides common caching strategies for dynamic content, such as API calls, third-party resources, and large or infrequently used local resources that you don't want precached.
Service Worker Toolbox provides an expressive approach to using those strategies for runtime requests. If you're not sure what service workers are or what they are for, start with the explainer doc.
What if I need precaching as well?
Then you should go check out sw-precache
before doing anything else. In addition to precaching static resources, sw-precache
supports optional runtime caching through a simple, declarative configuration that incorporates Service Worker Toolbox under the hood.
Install
Service Worker Toolbox is available through Bower, npm or direct from GitHub:
bower install --save sw-toolbox
npm install --save sw-toolbox
git clone https://github.com/GoogleChrome/sw-toolbox.git
Register your service worker
From your registering page, register your service worker in the normal way. For example:
navigator.serviceWorker.register('my-service-worker.js');
As implemented in Chrome 40 or later, a service worker must exist at the root of the scope that you intend it to control, or higher. So if you want all of the pages under /myapp/
to be controlled by the worker, the worker script itself must be served from either /
or /myapp/
. The default scope is the containing path of the service worker script.
For even lower friction, you can instead include the Service Worker Toolbox companion script in your HTML as shown below. Be aware that this is not customizable. If you need to do anything fancier than register with a default scope, you'll need to use the standard registration.
<script src="/path/to/sw-toolbox/companion.js" data-service-worker="my-service-worker.js"></script>
Add Service Worker Toolbox to your service worker script
In your service worker you just need to use importScripts
to load Service Worker Toolbox:
importScripts('bower_components/sw-toolbox/sw-toolbox.js'); // Update path to match your own setup.
Use the toolbox
To understand how to use the toolbox read the Usage and API documentation.
License
Copyright 2015-2016 Google, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
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
https://github.com/facebookincubator/create-react-app + Progressive Web App goodness
Webpack plugin that generates a service worker using sw-precache that will cache webpack's bundles' emitted assets. You can optionally pass sw-precache configuration options to webpack through this plugin.
Offline plugin (ServiceWorker, AppCache) for webpack (https://webpack.js.org/)
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