Preload with Media Queries for Responsive Loading

Use the media attribute on preload link tags to conditionally preload resources based on viewport size, device type, or user preferences.

Advanced

Detailed Explanation

Preloading with Media Queries

The media attribute on <link rel="preload"> lets you conditionally preload resources based on CSS media queries. This is essential for responsive designs where different resources are needed for different viewport sizes.

The Problem

Without media-aware preloading, you either:

  • Preload all responsive variants and waste bandwidth on devices that only use one
  • Preload none of them and miss the performance benefit

Syntax

<!-- Mobile hero image -->
<link rel="preload" href="/images/hero-mobile.webp" as="image"
      media="(max-width: 768px)" fetchpriority="high" />

<!-- Desktop hero image -->
<link rel="preload" href="/images/hero-desktop.webp" as="image"
      media="(min-width: 769px)" fetchpriority="high" />

The browser evaluates the media attribute and only fetches the resource if the media query matches the current viewport. If the user resizes the browser, the second resource is not fetched retroactively.

Common Responsive Preload Patterns

Different Images by Viewport

<link rel="preload" href="/hero-sm.webp" as="image"
      media="(max-width: 640px)" />
<link rel="preload" href="/hero-md.webp" as="image"
      media="(min-width: 641px) and (max-width: 1024px)" />
<link rel="preload" href="/hero-lg.webp" as="image"
      media="(min-width: 1025px)" />

Dark Mode Resources

<link rel="preload" href="/logo-light.svg" as="image"
      media="(prefers-color-scheme: dark)" />
<link rel="preload" href="/logo-dark.svg" as="image"
      media="(prefers-color-scheme: light)" />

High-DPI Displays

<link rel="preload" href="/hero@2x.webp" as="image"
      media="(-webkit-min-device-pixel-ratio: 2),
             (min-resolution: 192dpi)" />
<link rel="preload" href="/hero@1x.webp" as="image"
      media="(-webkit-max-device-pixel-ratio: 1.99),
             (max-resolution: 191dpi)" />

Bandwidth Savings

On a mobile device, preloading only the mobile hero image (50KB) instead of the desktop version (200KB) saves 150KB of bandwidth — significant on slow mobile connections. Across all resources on a page, media-aware preloading can save hundreds of kilobytes.

Limitations

  • Media queries are evaluated at preload time — they do not react to viewport changes after the page loads
  • Some browsers may still preload resources even if the media query does not match (speculative preloading)

Use Case

A responsive portfolio website preloads a 50KB mobile hero image for viewports under 768px and a 200KB desktop hero image for larger screens. It also preloads a light logo for dark mode and a dark logo for light mode. This saves 150KB+ of bandwidth on mobile while ensuring the LCP image is ready as fast as possible.

Try It — Preload Generator

Open full tool