Workbox | Google Developers
Extracto
<!-- No Description -->
Resumen
Resumen Principal
Workbox es una poderosa biblioteca de herramientas desarrollada por Google que facilita la creación y gestión de Service Workers para aplicaciones web progresivas (PWA). Esta herramienta está diseñada para simplificar tareas complejas relacionadas con el almacenamiento en caché, la estrategia de red, y la administración de activos offline, permitiendo a los desarrolladores implementar funcionalidades avanzadas de PWA sin tener que escribir código de bajo nivel. Workbox ofrece una serie de estrategias de caché predefinidas que se adaptan a distintos tipos de recursos, como imágenes, scripts o datos API, lo que mejora significativamente el rendimiento y la experiencia del usuario en condiciones de red variables. Además, proporciona herramientas para precaching, tiempos de ejecución de caché, y notificaciones push, convirtiéndose en una solución integral para la creación de aplicaciones web modernas, rápidas y confiables. Su integración con frameworks populares y su enfoque modular lo convierten en una opción preferida para equipos que buscan optimizar el ciclo de vida del caché y mejorar la resiliencia offline de sus aplicaciones.
Elementos Clave
- Estrategias de Caché Predefinidas: Workbox ofrece estrategias como Cache First, Network First, Stale-While-Revalidate, entre otras, que permiten a los desarrolladores definir cómo y cuándo se deben almacenar y recuperar los recursos, optimizando el rendimiento y la disponibilidad offline.
- Precaching Automatizado: La capacidad de precargar activos esenciales durante la instalación del Service Worker asegura que los recursos críticos estén disponibles desde la primera visita, mejorando tiempos de carga y experiencia inicial del usuario.
- Herramientas de Compilación Integradas: Workbox incluye plugins para Webpack, Rollup y otros bundlers, lo que facilita la generación automática de manifiestos de precaching y la integración en flujos de desarrollo modernos.
- Gestión Avanzada de Solicitudes en Tiempo de Ejecución: Permite interceptar y manejar solicitudes dinámicas con reglas personalizables, ofreciendo control fino sobre cómo se procesan los recursos que no están precargados, como llamadas a APIs o contenido generado dinámicamente.
Análisis e Implicaciones
Workbox representa una evolución significativa en el desarrollo de aplicaciones web progresivas, al democratizar el acceso a técnicas avanzadas de almacenamiento en caché y manejo de conectividad. Su adopción puede resultar en mejoras notables en el rendimiento web, la disponibilidad offline y la satisfacción del usuario, especialmente en entornos con conectividad intermitente. Además, al estandarizar buenas prácticas de Service Worker, Workbox contribuye a una web más rápida, confiable y equitativa.
Contexto Adicional
La documentación oficial de Workbox, disponible en Google Developers, proporciona guías detalladas, ejemplos prácticos y recursos para desarrolladores de todos los niveles. Es compatible con las últimas características de los navegadores modernos y se actualiza regularmente para mantenerse alineada con las mejores prácticas del ecosistema web.
Contenido
Performance
Stop waiting on the network! You can improve your web app's performance by caching and serving your files, powered by a service worker.
Resilience
Even on an unreliable connection, your web app can still work using the right runtime caching strategies.
Enhancement
Looking to build a progressive web app? Workbox makes it easy to create an offline first experience.
Why Workbox?
What's the API Like?
Below are a few examples of the Workbox API demonstrating some of the common approaches developers take in their service workers.
Cache Google Fonts
Wish you could rely on Google Fonts being available offline after the user has visited your site? Add a quick rule to serve them from the cache.
import {ExpirationPlugin} from 'workbox-expiration';
import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';
// Cache Google Fonts with a stale-while-revalidate strategy, with
// a maximum number of entries.
registerRoute(
({url}) => url.origin === 'https://fonts.googleapis.com' ||
url.origin === 'https://fonts.gstatic.com',
new StaleWhileRevalidate({
cacheName: 'google-fonts',
plugins: [
new ExpirationPlugin({maxEntries: 20}),
],
}),
);
Cache JavaScript and CSS
Make your JS and CSS ⚡ fast by returning the assets from the cache, while making sure they are updated in the background for the next use.
import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';
registerRoute(
({request}) => request.destination === 'script' ||
request.destination === 'style',
new StaleWhileRevalidate()
);
Cache Images
Images carry most of the weight for a web page. Use this rule to serve them quickly from the cache, while making sure you don’t cache them indefinitely, consuming your users' storage.
import {CacheableResponsePlugin} from 'workbox-cacheable-response';
import {CacheFirst} from 'workbox-strategies';
import {ExpirationPlugin} from 'workbox-expiration';
import {registerRoute} from 'workbox-routing';
registerRoute(
({request}) => request.destination === 'image',
new CacheFirst({
cacheName: 'images',
plugins: [
new CacheableResponsePlugin({
statuses: [0, 200],
}),
new ExpirationPlugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
}),
],
}),
);
Precache your Files
Use Workbox to precache assets in your web app using our CLI, Node module or webpack plugin.
CLI
workbox wizard
Node Module
const {generateSW} = require('workbox-build');
generateSW({
swDest: './build/sw.js',
globDirectory: './app',
globPatterns: '**/*.{js,css,html,png}',
});
webpack
const {GenerateSW} = require('workbox-webpack-plugin');
module.exports = {
// Other webpack config...
plugins: [
// Other plugins...
new GenerateSW(),
]
};
Offline Google Analytics
Want offline analytics for your offline PWA? No problem.
import * as googleAnalytics from 'workbox-google-analytics'; googleAnalytics.initialize();
Workbox @ Chrome Dev Summit
In this talk, Jeff Posnick gives an overview of Workbox's support for caching strategies, precaching, and handling navigation requests. It's filled throughout with real-world examples of how companies are using Workbox in production.
Case Studies
Contributors
[{ "type": "thumb-down", "id": "missingTheInformationINeed", "label":"Missing the information I need" },{ "type": "thumb-down", "id": "tooComplicatedTooManySteps", "label":"Too complicated / too many steps" },{ "type": "thumb-down", "id": "outOfDate", "label":"Out of date" },{ "type": "thumb-down", "id": "samplesCodeIssue", "label":"Samples / code issue" },{ "type": "thumb-down", "id": "otherDown", "label":"Other" }] [{ "type": "thumb-up", "id": "easyToUnderstand", "label":"Easy to understand" },{ "type": "thumb-up", "id": "solvedMyProblem", "label":"Solved my problem" },{ "type": "thumb-up", "id": "otherUp", "label":"Other" }]
Fuente: Google Developers