Source

Master the HTML source element for adaptive media delivery across devices and browsers

What Is the Source Element

In modern web development, the ability to deliver the right content to the right device at the right time is fundamental to creating exceptional user experiences. The HTML <source> element serves as a cornerstone of this adaptive content strategy, enabling developers to specify multiple media resources for <picture>, <audio>, and <video> elements. This powerful yet often underappreciated element forms the foundation of responsive media delivery, allowing websites to optimize both performance and visual presentation across an incredibly diverse landscape of devices, screen sizes, and browser capabilities.

Understanding the <source> element is essential for any developer seeking to build websites that perform well on everything from budget smartphones to high-resolution desktop displays. By providing the browser with choices about which resource to load, developers can ensure that users receive appropriately sized images, compatible media formats, and art-directed visuals that enhance rather than hinder their experience. This approach connects directly to our web development services, where we build interfaces that convert across every device your customers use.

The <source> HTML element represents a fundamental building block for adaptive media delivery on the web. As a void element, it has no closing tag and carries no content of its own--instead, it exists solely to provide the parent element with options for what content to display. This seemingly simple function belies the tremendous power it provides: the ability to offer the browser a choice between multiple media resources, each optimized for different conditions, devices, or capabilities.

The browser's selection process when encountering multiple <source> elements follows a clear priority order. It examines each <source> element in sequence, evaluating attributes like type and media to determine whether the resource is compatible with the current environment. This behavior ensures that content remains accessible regardless of the user's browser or device, a principle that lies at the heart of inclusive web design.

Key Capabilities of the Source Element

Understanding how the source element enables adaptive media delivery

Responsive Images

Use srcset and sizes attributes to serve appropriately sized images based on device screen size and pixel density, improving performance on all devices.

Art Direction

Serve different image crops for different viewport sizes using the picture element with media queries, ensuring important content remains visible.

Format Selection

Offer multiple image formats (WebP, AVIF, JPEG) and let browsers select the most efficient format they can decode.

Media Fallbacks

Provide multiple audio and video formats to ensure cross-browser compatibility without server-side transcoding.

Using Source with Picture Element

The <picture> element, introduced specifically to address the challenges of responsive images, works hand-in-hand with the <source> element to provide developers with unprecedented control over image delivery. Unlike the traditional <img> element, which offers a single source of truth, the <picture> element creates a context in which the browser can evaluate multiple image options and select the most appropriate one based on current conditions. This architecture empowers developers to implement both art direction--showing different crops or compositions for different viewport sizes--and format selection--serving next-generation image formats to capable browsers.

When implementing art direction using the <picture> element and <source> elements, developers define multiple source candidates, each potentially showing a different aspect of the subject matter or a different composition suited to the available space. The media attribute on each <source> element specifies a media query that the browser evaluates to determine whether that particular source is appropriate. For example, a landscape image might show a wide shot on desktop displays but focus on a central subject when viewed on mobile devices, ensuring that the most important visual elements remain prominent regardless of screen size.

Source Attributes for Picture Element

When used with the <picture> element, the <source> element supports a rich set of attributes that enable fine-grained control over image selection. The srcset attribute specifies a comma-separated list of image URLs along with descriptors that inform the browser about each image's size or pixel density. Each entry in the srcset consists of a URL followed by either a width descriptor (ending in "w") or a pixel density descriptor (ending in "x"). Width descriptors allow the browser to select images based on the display size needed, while pixel density descriptors enable selection based on the device's pixel density ratio.

The sizes attribute works in conjunction with srcset to provide additional context about how the image will be displayed. By specifying a series of source sizes--each consisting of a media condition and a corresponding width--the developer tells the browser how much space the image will occupy at different viewport sizes. The browser then uses this information, combined with the width descriptors in srcset, to calculate which image from the source set to download. This combination forms the foundation of modern responsive image implementation, enabling resolution switching that dramatically improves performance on resource-constrained devices. When implemented correctly with optimized images and proper source ordering, these techniques directly contribute to improved SEO performance by reducing page load times and improving Core Web Vitals scores.

For art direction scenarios where different images serve different viewport widths, the media attribute allows developers to specify arbitrary media queries that determine when each <source> should be considered. This enables dramatically different compositions for different screen sizes--perhaps a hero image that shows a full team photo on desktop but focuses on a single representative on mobile. The browser evaluates these media queries early in the page load process, ensuring that the correct image is selected before any resources are downloaded.

Responsive Image with srcset and sizes
1<picture>2 <source 3 media="(min-width: 1200px)" 4 srcset="hero-large.webp 1200w, hero-medium.webp 800w"5 sizes="1200px">6 <source 7 media="(min-width: 768px)" 8 srcset="hero-tablet.webp 800w"9 sizes="800px">10 <img 11 src="hero-mobile.jpg" 12 alt="Hero image that adapts to different screen sizes"13 srcset="hero-mobile.jpg 480w"14 sizes="100vw">15</picture>

Using Source with Audio and Video

The <source> element plays an equally important role in delivering audio and video content across the diverse landscape of web browsers. Unlike images, where format support is relatively consistent across modern browsers, audio and video codec support varies significantly. The <audio> and <video> elements use <source> elements to provide multiple format options, ensuring that content plays on as many browsers and devices as possible without requiring server-side transcoding or client-side JavaScript detection.

When providing audio content using the <audio> element with <source> children, developers typically include multiple format options to cover the browser ecosystem. Common audio formats include MP3 (supported by essentially all browsers), Ogg Vorbis (supported by Firefox and Chrome), and AAC (supported by Safari and Chrome). By ordering <source> elements from most efficient to least efficient, developers can ensure that capable browsers receive the smallest file size while older or less capable browsers still receive playable content.

Video delivery follows the same principle but with additional complexity due to the greater variety of video codecs and container formats. Common video formats include MP4 with H.264 video and AAC audio (the most widely supported format), WebM with VP8 or VP9 video and Vorbis audio (supported by Chrome, Firefox, and Edge), and increasingly, AV1 which offers superior compression. The <video> element's src attribute can point directly to a single video file, but using multiple <source> children provides the flexibility needed for comprehensive browser support. For media-rich sites, implementing proper video delivery through source elements reduces bandwidth costs and improves the experience for visitors on slower connections.

Key Attributes for Media Elements

The src attribute, when used with <audio> or <video> parent elements, specifies the URL of the media resource directly. The type attribute provides the MIME type of the media resource, optionally including codec information for container formats. For images, common type values include "image/webp", "image/avif", and "image/jpeg". For audio and video, the type includes both container and codec information. Including codec information allows the browser to make more informed decisions about whether it can play a file without downloading it, though this is most important for video where codec variations within container formats are common.

The media attribute, while more commonly associated with the <picture> element's art direction use cases, can also influence resource selection for audio and video when media conditions like screen size or orientation affect playback decisions. This attribute accepts any valid media query, enabling scenarios where different video sources serve different device orientations or screen sizes.

Video with Multiple Format Sources
1<video controls poster="video-thumbnail.jpg">2 <source 3 src="video.av1.mp4" 4 type="video/mp4; codecs=av01.0.05M.08">5 <source 6 src="video.webm" 7 type="video/webm; codecs=vp9">8 <source 9 src="video.mp4" 10 type="video/mp4">11 <p>12 Your browser doesn't support video playback.13 <a href="video.mp4">Download the video</a> instead.14 </p>15</video>

JavaScript Integration and Dynamic Sources

Beyond static HTML markup, the <source> element integrates seamlessly with JavaScript, enabling dynamic source manipulation that can respond to user interactions, network conditions, or application state changes. While the initial source selection happens when the page loads, developers can use JavaScript to modify, add, or remove <source> elements during the page's lifetime, implementing features like quality selection for video streaming, adaptive bitrate streaming, or user-controlled format switching. This dynamic capability extends the <source> element's utility far beyond initial page load, enabling sophisticated media experiences that adapt to changing conditions.

For video elements, the addSource() method allows programmatic insertion of new <source> elements at any point in the document lifecycle. This capability underlies many adaptive streaming implementations, where video quality dynamically adjusts based on available bandwidth. When network conditions change, JavaScript can add higher or lower quality sources, and the browser will select the most appropriate option from the available set. Similarly, removing sources using removeSource() or clearing all sources and adding new ones enables complete source set replacement, useful when implementing features like quality settings menus that let users explicitly choose their preferred video quality.

The source property of media elements provides direct access to the currently selected <source> element, enabling developers to inspect which source the browser has chosen and gather information about the active media resource. This can be valuable for analytics, quality monitoring, or user interface updates that reflect the current playback state. When multiple sources are available and the browser has selected one, this property reveals which option proved most suitable for the current environment.

Error handling for source loading requires attention to the media element's error events and properties. When a source fails to load--perhaps due to network issues, corrupted files, or format problems the browser couldn't detect until attempting playback--the media element's error property provides an error code, and the source property indicates which <source> element failed. This information enables sophisticated error handling: applications can log errors for debugging, notify users of playback problems, or attempt to recover by loading alternative sources.

Best Practices and Performance Optimization

Implementing <source> elements effectively requires attention to several best practices that ensure optimal user experiences while minimizing bandwidth consumption and page load times. The order of <source> elements significantly impacts both performance and user experience. Generally, sources should be ordered from most preferred to least preferred, allowing the browser to quickly find an acceptable option without unnecessary evaluation. The browser stops evaluating once it finds a compatible source, making ordering an important consideration for perceived performance.

Source Ordering

The order of <source> elements significantly impacts both performance and user experience. Generally, sources should be ordered from most preferred to least preferred, allowing the browser to quickly find an acceptable option without unnecessary evaluation. For responsive images, this typically means ordering by efficiency (smaller, more compressed formats first) or by art direction priority (mobile-optimized versions before desktop versions).

Fallback Content

Providing fallback content remains essential even in modern browsers. For <picture>, a fallback <img> element ensures that browsers without source set support--or when no source matches--still display an image. For <audio> and <video>, content between the opening and closing tags serves as fallback, typically including a download link or alternative playback instructions. While the vast majority of modern browsers support source elements, the small percentage of users on older browsers still deserves consideration.

Performance Optimization

Performance optimization through <source> elements extends beyond simply providing multiple options--it requires thoughtful source set construction that genuinely improves performance. For responsive images using srcset and sizes, the images in the source set should be generated at actual needed sizes rather than scaled-down versions of a single large image. Similarly, alternative formats should be properly optimized for their format--serving an unoptimized WebP file provides little benefit over a well-optimized JPEG.

Lazy loading considerations for <source> elements differ from lazy loading for regular images. While the loading="lazy" attribute works well for fallback <img> elements within <picture>, the <source> elements themselves don't support this attribute directly. However, the <picture> element can be lazy loaded as a whole, and the browser's source selection still occurs when the picture enters the viewport. Our performance optimization services can help you implement these techniques effectively across your entire site, and when you're ready to integrate intelligent media handling with automation, our AI automation services can take your media delivery to the next level.

Sources

  1. MDN Web Docs: The Media or Image Source element - Official documentation for <source> element attributes, usage with media elements, and browser support information.
  2. MDN Web Docs: Responsive images guide - Best practices for responsive images using srcset, sizes, and picture element.

Frequently Asked Questions

What is the difference between srcset and the picture element?

srcset with sizes provides resolution switching--serving the same image at different sizes based on device requirements. The picture element with media attributes enables art direction--showing entirely different images for different conditions, such as different crops for mobile versus desktop.

Can I use the source element with the img tag directly?

No, the source element is designed to work within picture, audio, or video elements. For img elements, use the srcset and sizes attributes directly on the img tag itself to achieve resolution switching.

What order should I list source elements?

List sources in order of preference, with the most efficient or preferred option first. The browser uses the first compatible source it encounters, so place your preferred format or size earlier in the list.

Do I need to include fallback content?

Yes. For picture elements, include a fallback img element as the last child. For audio and video, include text or download links between the opening and closing tags for browsers that can't play any provided format.

Build Better Web Experiences

Our team specializes in creating responsive, performant websites that work beautifully across all devices.