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
3 Hrs
53 Min
56 Seg

Reduciendo el tamaño del bundle

22/38
Resources

How to optimize your projects by minimizing dependencies?

In application development, it is common to face the challenge of managing dependencies efficiently. It is crucial to improve performance and optimize the delivery of our applications. In this article, we will explore strategies and tools to identify and reduce the impact of dependencies in our projects. Get ready to discover how to optimize your code effectively.

What tools can we use to analyze dependencies?

There are several tools and services that make it easier to analyze the impact of dependencies in our project:

  • Bundle Fogia: It is an online service that allows us to check how much each library influences the size of our bundle before and after installing them.

  • Webpack and its analysis plugin: By running an analysis with --analyze, we can directly see the impact of each dependency on our application.

What is the impact of loading complete libraries unnecessarily?

A common mistake is to load full libraries when few methods are used. Let's analyze the case of Lodash:

import _ from 'lodash'let result = _.get(data, 'key');

In the above example, we are importing the entire Lodash library when we only use the .get() method. This results in a waste of resources, as we load a lot of functionality that we don't need.

How to apply Tree Shaking effectively?

To avoid loading unnecessary code, we can employ tree shaking, a technique that helps eliminate dead code during the build process. For that, it is essential to use a proper syntax:

import get from 'lodash/get'let result = get(data, 'key');

By using method-specific import, we enable Webpack to perform tree shaking, including only the necessary parts of the library in the bundle. The syntax change as shown significantly reduces the bundle weight.

What to do with libraries that do not support tree shaking?

For example, the Moment.js library does not support tree shaking. In this case, we must look for alternative libraries that are more efficient. A good option is date-fns:

Steps to replace Moment.js with date-fns:

  1. Uninstall Moment.js:

    npm uninstall moment
  2. Install date-fns:

    npm install date-fns
  3. Replace Moment.js in the code:

    import { formatDistance, parseISO } from 'date-fns'
    let result = formatDistance(parseISO(date), new Date(), { addSuffix: true });

What results to expect when applying optimizations?

When implementing these strategies, the bundle weight of your project can make a world of difference. The result is that the bundle becomes much lighter, reducing the size from unnecessary Gigabytes (GB) to a few Kilobytes (KB), which is crucial for improving performance and user experience. The change in the final bundle structure will be substantial:

  • Initial weight: 1.5 MB.
  • Weight after optimization: 30 KB.

These measures not only optimize the loading time, but also the efficiency of your application by moving less data. Always remember to evaluate and decide if a library fits the real needs of your project.

Contributions 17

Questions 6

Sort by:

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

Para reducir el peso de moment, se puede usar este plugin https://www.npmjs.com/package/moment-locales-webpack-plugin que te permite elegir los idiomas que se quieren incluir en el bundle final.

En nuestro caso, necesitamos español, por lo tanto en el webpack config se agrega:

const MomentLocalesPlugin = require('moment-locales-webpack-plugin')

Y a plugins:

new MomentLocalesPlugin({
    localesToKeep: ['es'],
}),

Actualmente se estaba usando ingles en el sistema. Para usar español, en carouselItem.js ir donde se importa moment, y dejarlo así:

import moment from 'moment'
moment.locale('es')

Así el bundle queda mucho más liviano, y se usa fechas en español. Al parece, el paquete moment incluye internamente el ingles, en caso que no se use ningún paquete de idioma.

⬇️ Reduciendo el tamaño del bundle

<h4>Recursos</h4>

BundlePhobia

<h4>Apuntes</h4>
  • Podemos usar soluciones online para analizar que puede estar pesando dentro de nuestra aplicación una de ellas es bundle Phobia
  • Existen librerías que son “Tree Shakable”
    • Ayudan al empaquetador de solo sacar lo que se necesitan
  • Nos podemos ayudar de bundle Phobia para encontrar paquetes que sean más pequeños a la hora de hacer el bundle de nuestra aplicación

RESUMEN: Para reducir el tamaño de nuestro bundle es importante tomar en cuenta las dependencias que usamos y encontrar la forma de reducir el tamaño ya sea usando las funciones necesarias si es que la libreria es tree shakable o buscando una alternativa liviana

Probé el destructuring y no se redujo el tamaño inicial. Con la segunda opción “lodash/get” sí redujo el tamaño.

Pense que iba a optimizar moment
😃

Tree Shaking es la onda! 😄

Con BundlePhobia nos podemos ayudar para buscar las librerías similares a moment y así escoger la más eficiente.
Yo por ejemplo use dayjs y logre reducirla hasta 23.9 Kb

https://bundlephobia.com/[email protected]

Sin duda, es la clase del curso hasta ahora que más me ha impactado, es jodidamente maravilloso el tamaño final del bundle optimizado respecto al inicial.

**Esto fue asombroso **

Impresionante, que curso tan bueno. Felicitaciones!!!

que Interesante, me encanta este curso

Mi resultado: 😮

Al final me quedo con 31.7 kb

No importa si varia el resultado de esa manera verdad?
Me gustaria feedback, gracias 😄

utilizar lodash solo para eso, es como cortar plantas con una motosierra

Excelente clase.

Tengo una duda, para cuando utilizamos timepicker y datepicker ,… normalmente lo suelo usar con bootstrap y hacen uso de moment.js cuando los uso que me recomendarias para poder quitar moment y usar algo mas ligero… ya que he buscado y encontre pickdate.js pero no es muy bueno para las fechas… alguna sugerencia? para optimizar nuestros datepickers y timepickers . Gracias

👌

Excelente clase!

Waoo 😱 esto si que es optimizar