Course contentsShow
← Web Development
Lesson 2015 of 2,98237. Image and Asset OptimizationFree lesson

Type Attribute for Modern Image Formats

Use the type attribute in <source> to serve WebP or AVIF with automatic fallback to JPEG/PNG.

Type Attribute for Modern Image Formats

What you'll learn: How to use the type attribute in <picture> sources to serve cutting-edge image formats with automatic fallback to widely-supported formats.

The Problem: Different Browsers, Different Capabilities

Not every browser supports modern formats like WebP or AVIF yet. You want to serve these highly-compressed formats to browsers that understand them, but you need a safety net for older browsers that only handle JPEG or PNG.

How the Type Attribute Works

The type attribute in a <source> element tells the browser what format the image uses. Browsers evaluate each <source> from top to bottom and pick the first one they support. If they can't handle any of them, they fall back to the <img> tag.

Think of it like a restaurant menu with dietary preferences: the browser reads down the list looking for something it can "digest," skipping over formats it doesn't recognize.

Basic Syntax

<picture>
  <source srcset="photo.avif" type="image/avif">
  <source srcset="photo.webp" type="image/webp">
  <img src="photo.jpg" alt="Description">
</picture>

In this example:

  • Modern browsers grab the tiny AVIF file
  • Slightly older browsers get the WebP version
  • Legacy browsers receive the reliable JPEG

The browser automatically skips formats it doesn't support—no JavaScript needed.

Why This Matters

By declaring type="image/avif" or type="image/webp", you enable:

  • Smaller file sizes for capable browsers (often 30-50% reduction)
  • Zero-risk fallback for older browsers
  • Progressive enhancement without feature detection scripts

Key Takeaway: The type attribute lets you serve modern, efficient image formats while guaranteeing backward compatibility through automatic browser selection—giving you performance wins without breaking older browsers.