Skip to content

Commit 5621eca

Browse files
authored
Update pwa.md
1 parent 83b284a commit 5621eca

File tree

1 file changed

+67
-62
lines changed

1 file changed

+67
-62
lines changed

pwa.md

+67-62
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
1-
# Offline Mode
1+
# Modo sin conexión
22

3-
!> Este archivo aún no está traducido al español, estamos traduciendo... si gustas, puedes ayudar.
3+
[Progressive Web Apps](https://developers.google.com/web/progressive-web-apps/) (PWA) son experiencias que combinan lo mejor de la web con lo mejor de las aplicaciones. Podemos mejorar nuestro sitio web con trabajadores de servicio para que funcione **sin conexión** o en redes de baja calidad.
44

5-
[Progressive Web Apps](https://developers.google.com/web/progressive-web-apps/) (PWA) are experiences that combine the best of the web with the best of apps. We can enhance our website with service workers to work **offline** or on low-quality networks.
5+
También es muy fácil de usar.
66

7-
It is also very easy to use it.
7+
## Crear serviceWorker
88

9-
## Create serviceWorker
9+
Crea un archivo `sw.js` en el directorio raíz de tu proyecto y copia el siguiente código:
1010

11-
Create a `sw.js` file in your documents root directory and copy the following code:
12-
13-
*sw.js*
11+
_sw.js_
1412

1513
```js
1614
/* ===========================================================
@@ -21,97 +19,104 @@ Create a `sw.js` file in your documents root directory and copy the following co
2119
* Register service worker.
2220
* ========================================================== */
2321

24-
const RUNTIME = 'docsify'
22+
const RUNTIME = 'docsify';
2523
const HOSTNAME_WHITELIST = [
2624
self.location.hostname,
2725
'fonts.gstatic.com',
2826
'fonts.googleapis.com',
29-
'unpkg.com'
30-
]
31-
32-
// The Util Function to hack URLs of intercepted requests
33-
const getFixedUrl = (req) => {
34-
var now = Date.now()
35-
var url = new URL(req.url)
36-
37-
// 1. fixed http URL
38-
// Just keep syncing with location.protocol
39-
// fetch(httpURL) belongs to active mixed content.
40-
// And fetch(httpRequest) is not supported yet.
41-
url.protocol = self.location.protocol
42-
43-
// 2. add query for caching-busting.
44-
// Github Pages served with Cache-Control: max-age=600
45-
// max-age on mutable content is error-prone, with SW life of bugs can even extend.
46-
// Until cache mode of Fetch API landed, we have to workaround cache-busting with query string.
47-
// Cache-Control-Bug: https://bugs.chromium.org/p/chromium/issues/detail?id=453190
27+
'cdn.jsdelivr.net',
28+
];
29+
30+
// La función de utilidad para modificar las URL de las solicitudes interceptadas
31+
const getFixedUrl = req => {
32+
const now = Date.now();
33+
const url = new URL(req.url);
34+
35+
// 1. corregir URL http
36+
// Simplemente mantén la sincronización con location.protocol
37+
// fetch(httpURL) pertenece a contenido mixto activo.
38+
// Y fetch(httpRequest) aún no es compatible.
39+
url.protocol = self.location.protocol;
40+
41+
// 2. agregar consulta para romper la caché.
42+
// Las páginas de GitHub se sirven con Cache-Control: max-age=600
43+
// max-age en contenido mutable es propenso a errores, con la vida de los errores del SW puede incluso extenderse.
44+
// Hasta que aterrice el modo de caché de la API Fetch, tenemos que evitar problemas de caché con una cadena de consulta.
45+
// Bug de Cache-Control: https://bugs.chromium.org/p/chromium/issues/detail?id=453190
4846
if (url.hostname === self.location.hostname) {
49-
url.search += (url.search ? '&' : '?') + 'cache-bust=' + now
47+
url.search += (url.search ? '&' : '?') + 'cache-bust=' + now;
5048
}
51-
return url.href
52-
}
49+
return url.href;
50+
};
5351

5452
/**
5553
* @Lifecycle Activate
56-
* New one activated when old isnt being used.
54+
* Se activa uno nuevo cuando el antiguo no se está utilizando.
5755
*
58-
* waitUntil(): activating ====> activated
56+
* waitUntil(): activar ====> activado
5957
*/
6058
self.addEventListener('activate', event => {
61-
event.waitUntil(self.clients.claim())
62-
})
59+
event.waitUntil(self.clients.claim());
60+
});
6361

6462
/**
65-
* @Functional Fetch
66-
* All network requests are being intercepted here.
63+
* @Funcional Fetch
64+
* Todas las solicitudes de red se interceptan aquí.
6765
*
6866
* void respondWith(Promise<Response> r)
6967
*/
7068
self.addEventListener('fetch', event => {
71-
// Skip some of cross-origin requests, like those for Google Analytics.
69+
// Omitir algunas solicitudes entre dominios, como las de Google Analytics.
7270
if (HOSTNAME_WHITELIST.indexOf(new URL(event.request.url).hostname) > -1) {
7371
// Stale-while-revalidate
74-
// similar to HTTP's stale-while-revalidate: https://www.mnot.net/blog/2007/12/12/stale
75-
// Upgrade from Jake's to Surma's: https://gist.github.com/surma/eb441223daaedf880801ad80006389f1
76-
const cached = caches.match(event.request)
77-
const fixedUrl = getFixedUrl(event.request)
78-
const fetched = fetch(fixedUrl, { cache: 'no-store' })
79-
const fetchedCopy = fetched.then(resp => resp.clone())
80-
81-
// Call respondWith() with whatever we get first.
82-
// If the fetch fails (e.g disconnected), wait for the cache.
83-
// If there’s nothing in cache, wait for the fetch.
84-
// If neither yields a response, return offline pages.
72+
// similar a stale-while-revalidate de HTTP: https://www.mnot.net/blog/2007/12/12/stale
73+
// Actualización de la versión de Jake a la de Surma: https://gist.github.com/surma/eb441223daaedf880801ad80006389f1
74+
const cached = caches.match(event.request);
75+
const fixedUrl = getFixedUrl(event.request);
76+
const fetched = fetch(fixedUrl, { cache: 'no-store' });
77+
const fetchedCopy = fetched.then(resp => resp.clone());
78+
79+
// Llama a respondWith() con lo que obtengamos primero.
80+
// Si la recuperación falla (por ejemplo, desconexión), espera la caché.
81+
// Si no hay nada en la caché, espera la recuperación.
82+
// Si ninguno de ellos proporciona una respuesta, devuelve páginas sin conexión.
8583
event.respondWith(
8684
Promise.race([fetched.catch(_ => cached), cached])
8785
.then(resp => resp || fetched)
88-
.catch(_ => { /* eat any errors */ })
89-
)
86+
.catch(_ => {
87+
/* come cualquier error */
88+
})
89+
);
9090

91-
// Update the cache with the version we fetched (only for ok status)
91+
// Actualiza la caché con la versión que recuperamos (solo para estados ok)
9292
event.waitUntil(
9393
Promise.all([fetchedCopy, caches.open(RUNTIME)])
94-
.then(([response, cache]) => response.ok && cache.put(event.request, response))
95-
.catch(_ => { /* eat any errors */ })
96-
)
94+
.then(
95+
([response, cache]) =>
96+
response.ok && cache.put(event.request, response)
97+
)
98+
.catch(_ => {
99+
/* come cualquier error */
100+
})
101+
);
97102
}
98-
})
103+
});
99104
```
100105

101-
## Register
106+
## Registrar
102107

103-
Now, register it in your `index.html`. It only works on some modern browsers, so we need to judge:
108+
Ahora, regístralo en tu `index.html`. Solo funciona en algunos navegadores modernos, así que debemos verificar:
104109

105-
*index.html*
110+
_index.html_
106111

107112
```html
108113
<script>
109114
if (typeof navigator.serviceWorker !== 'undefined') {
110-
navigator.serviceWorker.register('sw.js')
115+
navigator.serviceWorker.register('sw.js');
111116
}
112117
</script>
113118
```
114119

115-
## Enjoy it
120+
## Disfrútalo
116121

117-
Release your website and start experiencing magical offline feature. :ghost: You can turn off Wi-Fi and refresh the current site to experience it.
122+
Publica tu sitio web y comienza a experimentar la mágica función sin conexión. :ghost: Puedes apagar el Wi-Fi y actualizar el sitio actual para experimentarlo.

0 commit comments

Comments
 (0)