Image Optimization
Overview
Images typically account for over 60% of a webpage's total download size. The <img> tag is how we embed them, but if used improperly, it completely destroys performance. Modern HTML requires strict optimization attributes: loading="lazy" prevents the browser from downloading images that are hidden far down the page until the user actually scrolls to them, saving massive amounts of bandwidth. Explicitly defining width and height prevents 'Cumulative Layout Shift' (CLS), a jarring visual bug where the page violently jumps around as images finish downloading.
Syntax
<!-- The absolute minimum safe image tag in modern HTML -->
<img
src="/assets/hero-banner.jpg"
alt="A diverse team of developers collaborating around a laptop"
width="1200"
height="600"
loading="lazy"
decoding="async"
>Common Pitfalls
- Omitting the
altattribute. This is a severe accessibility violation. If an image fails to load, or if a visually impaired user relies on a screen reader, thealttext is the only way they understand the image's context. If an image is purely decorative, you must still includealt=""(empty string) so screen readers know to skip it safely. - Not providing
widthandheightattributes. Without them, the browser doesn't know how much vertical space to reserve for the image before it downloads, causing the text below it to suddenly snap downwards once the image appears.
Interview Questions
width and height attributes to an <img> tag improve?Cumulative Layout Shift (CLS). Reserving the exact aspect ratio space in the layout before the image loads prevents the UI from shifting, which Google heavily monitors for SEO rankings.
Real-World Example
A highly optimized profile picture inside a React component.
<!--
decoding="async" allows the browser to decode the image in parallel,
preventing it from freezing the main thread while rendering.
-->
<img
src="user_avatar_256.webp"
alt="Kartik Rai profile picture"
width="256"
height="256"
loading="lazy"
decoding="async"
class="rounded-full shadow-lg"
>Check Your Knowledge
Test your understanding of Image Optimization with these quick questions.