appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Images and fonts without slowing the page

Lesson 3 of 411 minIntermediate

Responsive images, modern formats, lazy loading and font loading that avoids layout jumps.

Images and fonts are usually the heaviest part of a page. A few attributes make a large difference.

<img
  src="photo-800.webp"
  srcset="photo-400.webp 400w, photo-800.webp 800w, photo-1600.webp 1600w"
  sizes="(min-width: 60rem) 50vw, 100vw"
  width="800" height="533"
  alt="A mountain lake at sunrise"
  loading="lazy" decoding="async">
  • srcset and sizes let the browser download the smallest file that looks sharp on that screen.
  • width and height reserve the space so the page does not jump (CLS).
  • loading="lazy" delays images below the fold. Do not lazy-load the main image at the top (the LCP image). Give it fetchpriority="high" instead.
  • Use WebP or AVIF for photos and SVG for icons and logos.

Art direction with picture

<picture>
  <source type="image/avif" srcset="hero.avif">
  <source type="image/webp" srcset="hero.webp">
  <img src="hero.jpg" width="1200" height="600" alt="Team at work">
</picture>

Fonts

@font-face {
  font-family: "Nunito";
  src: url("/fonts/nunito.woff2") format("woff2");
  font-display: swap;
}
  • Host fonts yourself in WOFF2. It avoids a third-party connection and can improve privacy.
  • font-display: swap shows text immediately in a fallback font and swaps when the font arrives.
  • Preload only the one or two fonts used above the fold: <link rel="preload" as="font" type="font/woff2" crossorigin>.
  • Subset the font to the characters you need.

CarefulAlways write meaningful alt text. Use alt="" only for purely decorative images, so screen readers skip them.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. Why set width and height on an img?
2. Should the main hero image at the top use loading="lazy"?
3. What does font-display: swap do?

Key terms