Is there a way to prevent these images from loading on mobile to
increase the performance/load time?
Yes.
The srcset
attribute is explicitly intended for downloading different image files depending on context.
The one caveat is that you need to declare an image (or a fallback) for every environment.
But that won't prevent you from using as your fallback an equivalent-to-null image (ie. a 1x1 pixel transparent png) declared inline using a base-64 Data URL
, which looks like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==
srcset
and sizes
syntax:
The finished <img>
element, with files indicated for desktop and mobile environments will look like something like this:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
srcset="/my-image-folder/desktop.png 640w,
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg== 1w"
sizes="(min-width: 641px) 640px,
(max-width: 640px) 1px"
alt="Alternative Text for My Image"
/>
This <img>
element will only download and display the desktop.png
image if the browser viewport width is 641px
or greater.
Otherwise it will display a 1x1
pixel transparent png.
Working Example:
<h2>Narrow and Widen your Browser Viewport in Full Page</h2>
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
srcset="https://via.placeholder.com/620x100 620w,
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg== 1w"
sizes="(min-width: 641px) 620px,
(max-width: 640px) 1px"
alt="Alternative Text for My Image"
/>
Browser support
For contemporary browser support for srcset
and sizes
attributes, see:
More Info (plus tutorial)
For more in-depth info and a tutorial on using srcset
and sizes
to build Responsive Images
, see:
Update in 2021
The Data URL used in the answer above:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==
works, but it's a bit scrappy and pretty unclear what it's supposed to represent (unless you already know what it is).
I've since realised that:
data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'/%3E
works just as well and is both shorter and cleaner and more human-readable.