Entendiendo el rendimiento

1

Todo lo que aprender谩s sobre optimizaci贸n web

2

驴Vale el esfuerzo optimizar un sitio web?

3

驴Cu谩ndo realmente un sitio es r谩pido o lento?

Antes de optimizar...

4

Aprendiendo a medir

5

User Performance Metrics

6

Nuestro proyecto

Cr铆tical Rendering Path

7

Etapas de render del navegador

8

Network waterfall y recursos que bloquean el navegador

9

Priorizaci贸n de recursos

10

Preloading y prefetching de recursos

11

Fases Paint y Layout del Critical Render Path

CSS

12

Detectando Paints costosos y optimizando animaciones

13

Bloqueos y complejidad en selectores

WebFonts

14

WebFonts y su impacto en rendimiento

Im谩genes, Iconos y SVG

15

Im谩genes, formato y compresi贸n

16

Im谩genes y compresi贸n

17

驴WebFont, Imagen o SVG?

18

T茅cnicas avanzadas con Lazy Loading

19

T茅cnicas avanzadas con Responsive Loading

Aplicaciones JavaScript

20

JavaScript y aplicaciones modernas y Utilizando un servidor de producci贸n

21

Analizando el bundle de la aplicaci贸n

22

Reduciendo el tama帽o del bundle

23

Code Splitting

24

Lazy Module Loading

25

Llevando los listeners a otro nivel

26

Instalando Modal video

27

Lazy loading del modal

28

Moviendo la carga de rendering hacia el servidor: Server Side Rendering

29

Aplicando SSR

30

Pre-renderizando el contenido: Static Generation

Cach茅

31

C贸mo funciona el Cach茅 de recursos y CDN

32

Deploy en Netlify y automatizaci贸n de contenido en GitHub Actions

33

Aplicando Github Actions

34

Interceptando los requests del navegador con Service Workers

Performance Budget

35

Performance budget y auditorias automatizadas

36

Automatizando una auditor铆a con Lighthouse CI

37

Medidas reales y monitoreo constante

Conclusiones

38

Conclusiones

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
6 Hrs
42 Min
42 Seg

Interceptando los requests del navegador con Service Workers

34/38
Resources

What is a Service Worker and how does it optimize the cache?

A Service Worker is a revolutionary technology that gives developers more control over the interactions between the browser and the server. Imagine that you have at your disposal a virtually tiny and efficient layer that acts as a thorough intermediary between your web application and the Internet network. But how can a Service Worker optimize the caching of static resources such as images, CSS or JavaScript?

What are the initial steps to implement a Service Worker?

The implementation of a Service Worker in your application can be divided into essential steps:

  1. Installing the Service Worker: The Service Worker must be installed in the browser. This involves registering the Service Worker in the application, usually in the service-worker.js file located in the root of the project.

    if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/service-worker.js').then(registration => { console.log('Service Worker successfully registered:', registration); }).catch(error => { console.log('Error registering the Service Worker:', error); }); });}
  2. Fetch Requests Interception: Configure a listener to intercept all resource requests made by the browser. This interceptor decides if the resource can be reused from the cache.

  3. Cache Management: Determine what to do if the resource requested by the browser is in the cache or if it needs to be requested again from the server.

How does the internal logic of a Service Worker work for caching?

Within the Service Worker, decisions about cache usage are critical. The logic can be summarized as follows:

  • Cache Check: When the browser makes a request, it checks to see if a cached version of that resource already exists.

    self.addEventListener('fetch', event => { event.respondWith( caches.match(event.request) .then(cachedResponse => { // If the response is cached, it is returned to the browser directly. if (cachedResponse) { return cachedResponse; }        
     // If not, a normal request is made to the network. return fetch(event.request).then(networkResponse => { // The new response is validated and cached for future requests. if (networkResponse.status === 200) { caches.open('my-resource-cache') .then(cache => { cache.put(event.request, networkResponse.clone()); }); }); } return networkResponse; });} ) );

What additional benefits do Service Workers offer?

Service Workers are not only useful for caching. Here are some additional applications that maximize their potential:

  • Offline Experiences: They allow web applications to run offline by prefetching the necessary resources.
  • Resource Prefetching: Anticipate user needs by loading resources before they are requested.
  • Progressive Web Applications (PWAs): Improve usability and performance, giving web applications a look and feel similar to native apps.

Having realized this potential, we encourage all developers to explore more about Service Workers. Implementing them will not only improve the efficiency of your application, but also offer an enriched user experience. Continue learning and dare to implement these advanced technologies!

Contributions 8

Questions 3

Sort by:

Want to see more contributions, questions and answers from the community?

Service Workers

Los聽Service workers聽act煤an esencialmente como proxy servers asentados entre las aplicaciones web, el navegador y la red (cuando est谩 accesible).

Se pueden utilizar para:

  • Generar cache
  • Pre-fetching
  • Offline experiences
  • Background services

El mapeo de responses, y la comparacion por assets usando una regexp no agrega mayor costo en performance? Dado que las regexp son batante costosas.

Por otro lado, el hecho de guardar las imagenes solo del mismo dominio de la app es una cosa del proyecto como tal, o no es recomendable hacer cache de imagenes (por ejemplo) de un S3?

Este tema es un poco complicado, honestamente no pude entender la clase

Si estas utilizando Next js puedes leer este post. https://dev.to/josedonato/adding-a-service-worker-into-your-next-js-application-1dib 馃槃

Debemos llamar el service worker en el index.template.html de la siguiente forma:

    <script>
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', () => {
          navigator.serviceWorker.register('/service-worker.js')
        })
      }
    </script>

Esta implementaci贸n la pude ver en el curso de JS profesional del profe Richard B. Kaufman. Creo que me fue m谩s f谩cil entender recordando lo visto en esa clase. Por supuesto igual pienso que e profesor Jonathan ha venido explicando muy bien cada tema. Excelente.

El video est谩 fallando, al menos desde chrome

馃憣