Imágenes responsivas para tu sitio web

Rate this content
Bookmark

¿Por qué molestarse en optimizar imágenes? Las imágenes a menudo representan la mayor parte de los bytes descargados en una página web. Como resultado, optimizar imágenes puede generar mejoras significativas en el rendimiento de tu sitio web.

7 min
05 Jun, 2023

Video Summary and Transcription

La charla aborda varios aspectos de servir imágenes en sitios web, incluyendo dónde almacenar imágenes, opciones de transformación de imágenes y formatos de imágenes. También explora diferentes enfoques para manejar versiones y tamaños de imágenes, como prepararlas de antemano o usar un servidor proxy. El orador destaca la importancia de optimizar imágenes para el rendimiento y menciona el progreso realizado en la adopción de nuevos formatos de imagen. En general, la charla brinda información sobre las mejores prácticas para administrar y servir imágenes dinámicas responsivas.

Available in English

1. Introducción a las imágenes dinámicas y responsivas

Short description:

Hola a todos, mi nombre es Sergei Bucharov y estoy muy emocionado de hablar hoy sobre imágenes dinámicas y responsivas en la conferencia JS Nation. Soy de Fullstack Sber y hoy hablaré sobre diferentes formas de servir imágenes en tu sitio. Recientemente leí un informe sobre el estado de la web y me di cuenta de cuánto más se necesita hacer en este tema. Intentemos responder estas preguntas. Primera pregunta. ¿Dónde debo almacenar mis imágenes, localmente o de forma remota? ¿Qué operaciones de transformación podemos realizar? La segunda pregunta es, ¿en qué formato deben mantenerse las imágenes? Según el archivo HTTP, las posiciones principales están ocupadas por JIF, JPG y PNG, lo cual puede ayudar, pero me preocupa.

dinámicas y responsivas en la conferencia JS Nation. Soy de Fullstack Sber y hoy hablaré sobre diferentes formas de servir imágenes en tu sitio. Recientemente leí un informe sobre el estado de la web y me di cuenta de cuánto más se necesita hacer en este tema.

Un tercio de las páginas utiliza el conjunto SRC, pero dos tercios no lo hacen. Primero, en 2014, los atributos del conjunto SRC, el atributo de tamaños y el elemento picture han permitido a la oficina simular recursos adaptables durante casi una década. El elemento picture se utiliza mucho menos que el conjunto SRC. A estas alturas, probablemente sepas que implementar la carga de imágenes no es un problema fácil. Surgieron muchas preguntas de inmediato, incluyendo algunas importantes como 1. ¿Dónde debo almacenar mis imágenes, localmente o de forma remota? 2. ¿En qué formato deben mantenerse las imágenes? 3. ¿Cómo manejo las transformaciones de imágenes y dónde guardo las diferentes versiones de la misma imagen? 4. ¿Cuántos tamaños de imagen debo proporcionar a los navegadores web? 5. ¿Cómo integro todo en mi aplicación existente? Ciertamente, hay una gran cantidad de soluciones listas para usar disponibles, por lo que puedes elegir una, pero más sobre ellas más adelante. Intentemos responder estas preguntas.

Primera pregunta. ¿Dónde debo almacenar mis imágenes, localmente o de forma remota? Depende de muchos factores, tanto técnicos como comerciales, por ejemplo, 1. el número de imágenes 2. facilidad de soporte 3. el número total de operaciones de transformación 4. el plan de imágenes, si estás utilizando IMAGE CDM 5. la frecuencia de cambios de diseño 6. y muchos otros ¿Qué operaciones de transformación podemos realizar? Por lo general, divido estas operaciones en dos grupos, principales y adicionales. El grupo principal incluye recortar, redimensionar, filtrar, optimizar y transformar. Y, por supuesto, debes recordar la protección. El grupo adicional incluye desenfoque, agregar texto, voltear, contornos y sombras, y muchos otros efectos especiales. Por lo tanto, debes pensar en tus objetivos y elegir el tipo de almacenamiento. Si solo necesitas recortar y redimensionar, puedes hacerlo en tu servidor. Te mostraré cómo hacerlo más adelante.

La segunda pregunta es, ¿en qué formato deben mantenerse las imágenes? Según el archivo HTTP, las posiciones principales están ocupadas por JIF, JPG y PNG, lo cual puede ayudar, pero me preocupa. A 0.22% una porción WWF de 3Py es tan pequeña que ni siquiera está etiquetada en el gráfico.

2. Manejo de Transformaciones de Imágenes y Opciones de Carga

Short description:

Y aunque el 0.22% puede no parecer mucho, en comparación con el año pasado, representa un progreso considerable. Lentamente, los formatos antiguos están dando paso a los nuevos, como deberían. Los nuevos formatos superan ampliamente a los antiguos. Este gráfico muestra bits por píxel por formato. La tercera pregunta es, ¿cómo manejo las transformaciones de imágenes y dónde guardo las diferentes versiones de la misma imagen? Hay muchas herramientas para la optimización y transformación de imágenes. La cuarta pregunta es cuántos tamaños de imagen proporcionar a los navegadores web. Esta es una pregunta interesante y todo depende de tu diseño. La última pregunta es cómo subir todo a mi aplicación existente. La opción 1 es preparar varias versiones de la misma imagen de antemano y guardarlas en tu servidor. La opción 2 es la misma, pero puedes guardar las imágenes en tu CDN regular. La opción 3 es usar un servidor proxy para la optimización y transformación de tus imágenes. Si te sientes cómodo con Nginx y Docker, por ejemplo, puedes configurar un servidor proxy en un servidor remoto de inmediato. Hay muchos proyectos de código abierto diferentes para este propósito. Espero que disfrutes mucho en la conferencia JS Nation. Gracias por tu tiempo.

Y aunque el 0.22% puede no parecer mucho, en comparación con el año pasado, representa un progreso considerable. Lentamente, los formatos antiguos están dando paso a los nuevos, como deberían. Los nuevos formatos superan ampliamente a los antiguos. Pronto te darás cuenta de eso.

Este gráfico muestra bits por píxel por formato. Como puedes ver, un WWF está más comprimido que un WP o JPG. El WWF es un formato muy joven, cuyos codificadores han estado iterando rápidamente. Al responder a la pregunta de qué formato deben tener las imágenes, se incrementó el uso de formatos modernos como WWF y WP, y por supuesto JPG, donde sin él, se redujo el uso de formatos como JF y PNG.

La tercera pregunta es, ¿cómo manejo las transformaciones de imágenes y dónde guardo las diferentes versiones de la misma imagen? Hay muchas herramientas para la optimización y transformación de imágenes. Aquí tienes algunas de ellas. Este es un ejemplo de una etiqueta de imagen con los atributos src y sizes, la forma familiar de especificar la ubicación de tu imagen. Los navegadores que no admiten srcset y sizes usarán src como alternativa. Con sizes, especificas el tamaño de la imagen y en qué situación debe mostrarse. Esto se hace mediante una combinación de una consulta de medios y el ancho de una imagen. Con srcset, especificas una lista de imágenes y diferentes tamaños. Otro objetivo perfectamente legítimo con imágenes responsivas no es solo mostrar diferentes tamaños de la misma imagen, sino mostrar diferentes imágenes. La etiqueta picture tiene la misma lógica, pero tiene una etiqueta source.

La cuarta pregunta es cuántos tamaños de imagen proporcionar a los navegadores web. Esta es una pregunta interesante y todo depende de tu diseño. Por ejemplo, se proporcionan muchas imágenes en el sitio de monger. ¿Muchas, verdad?

La última pregunta es cómo subir todo a mi aplicación existente. La opción 1 es preparar varias versiones de la misma imagen de antemano y guardarlas en tu servidor. Es una buena opción si no tienes miles de imágenes y el diseño no cambia con mucha frecuencia. La opción 2 es la misma, pero puedes guardar las imágenes en tu CDN regular. La opción 3 es usar un servidor proxy para la optimización y transformación de tus imágenes. Si te sientes cómodo con Nginx y Docker, por ejemplo, puedes configurar un servidor proxy en un servidor remoto de inmediato. Hay muchos proyectos de código abierto diferentes para este propósito. Por ejemplo, Fumba, ImageProxy, PicFit y otros. También puedes escribir tu propio optimizador de imágenes, por ejemplo, he escrito uno en Nginx, puedes verlo en GitHub. La ventaja es que puedes crear tu propia estructura de URL y utilizar solo la operación que necesitas. Y, por supuesto, si la opción 3 no es lo tuyo, puedes usar ImageCDN. Por ejemplo, Codinary, Amazon, Netlify, nginx, ng-optim, Filestack, Cloudflare y muchos otros. Espero que disfrutes mucho en la conferencia JS Nation. Gracias por tu tiempo. ¡Adiós!

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Too much JavaScript is getting you down? New frameworks promising no JavaScript look interesting, but you have an existing React application to maintain. What if Qwik React is your answer for faster applications startup and better user experience? Qwik React allows you to easily turn your React application into a collection of islands, which can be SSRed and delayed hydrated, and in some instances, hydration skipped altogether. And all of this in an incremental way without a rewrite.
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Our understanding of performance & user-experience has heavily evolved over the years. Web Developer Tooling needs to similarly evolve to make sure it is user-centric, actionable and contextual where modern experiences are concerned. In this talk, Addy will walk you through Chrome and others have been thinking about this problem and what updates they've been making to performance tools to lower the friction for building great experiences on the web.
JSNation 2023JSNation 2023
26 min
When Optimizations Backfire
Top Content
Ever loaded a font from the Google Fonts CDN? Or added the loading=lazy attribute onto an image? These optimizations are recommended all over the web – but, sometimes, they make your app not faster but slower.
In this talk, Ivan will show when some common performance optimizations backfire – and what we need to do to avoid that.

Workshops on related topic

React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
React Advanced Conference 2023React Advanced Conference 2023
148 min
React Performance Debugging
Workshop
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Vue.js London 2023Vue.js London 2023
49 min
Maximize App Performance by Optimizing Web Fonts
WorkshopFree
You've just landed on a web page and you try to click a certain element, but just before you do, an ad loads on top of it and you end up clicking that thing instead.
That…that’s a layout shift. Everyone, developers and users alike, know that layout shifts are bad. And the later they happen, the more disruptive they are to users. In this workshop we're going to look into how web fonts cause layout shifts and explore a few strategies of loading web fonts without causing big layout shifts.
Table of Contents:What’s CLS and how it’s calculated?How fonts can cause CLS?Font loading strategies for minimizing CLSRecap and conclusion
React Summit 2022React Summit 2022
50 min
High-performance Next.js
Workshop
Next.js is a compelling framework that makes many tasks effortless by providing many out-of-the-box solutions. But as soon as our app needs to scale, it is essential to maintain high performance without compromising maintenance and server costs. In this workshop, we will see how to analyze Next.js performances, resources usage, how to scale it, and how to make the right decisions while writing the application architecture.