Sub topic 14
Checking Which Image Was Chosen
What this chapter assumes
You have read the earlier chapters on srcset, sizes, and picture. You know that the browser, not your code, picks the file. You also know the difference between CSS pixels and device pixels. This chapter is about verifying that choice. You will find out which file loaded, whether it was a sensible one, and why it was not the one you expected.
Why you have to check
A responsive image that is wrong still renders. If sizes says 100vw but the image is shown at a third of the viewport, the page looks fine. It also downloads a file about three times wider than it needs. If a type value has a typo, the browser quietly falls through to the JPEG in the img. Nothing looks broken in either case. You only see these mistakes by inspecting what the browser did.
The browser's choice depends on four inputs:
- The viewport width.
- The
sizesvalue, which gives the slot width in CSS pixels. - The device pixel ratio.
- The cache.
You can read the first three. The cache is the one that most often confuses a test.
Reading currentSrc
Every img element has a currentSrc property. It holds the absolute URL of the file the browser selected. This works the same way when the img is inside a picture. The source elements have no currentSrc, so always read it from the img.
const img = document.querySelector('img');
console.log(img.currentSrc);
console.log(window.devicePixelRatio);Run this in the console and you get the chosen URL and the pixel ratio. Two details matter:
currentSrccan be an empty string if the browser has not finished choosing a candidate. That happens when you run the code too early.- The selection can change later. If the user resizes the window or rotates the device, the browser may pick again.
A more useful version waits for the image to load. It also compares the file's intrinsic width with the width the image needs.
function describe(img) {
const dpr = window.devicePixelRatio;
const needed = Math.round(img.clientWidth * dpr);
return {
file: img.currentSrc.split('/').pop(),
displayedCssPx: img.clientWidth,
dpr: dpr,
neededDevicePx: needed,
fileWidth: img.naturalWidth,
ratio: needed ? +(img.naturalWidth / needed).toFixed(2) : null
};
}
function report() {
const rows = [];
document.querySelectorAll('img').forEach((img) => rows.push(describe(img)));
console.table(rows);
}
if (document.readyState === 'complete') {
report();
} else {
window.addEventListener('load', report);
}The ratio column is the number to watch:
| Ratio | Meaning |
|---|---|
| About 1.0 | The file matches the pixels the screen needs. |
| Between 1.0 and 2.0 | Typical. Your candidates come in steps, so some overshoot is normal. |
| Above 2.0 | The file is much larger than needed. Check `sizes` or add a smaller candidate. |
| Below 1.0 | The image is being upscaled and will look soft. Check for a missing large candidate. |
Note that naturalWidth is the intrinsic width of the selected file. For a w-descriptor candidate it should match the number you declared. If it does not, the declared descriptor is wrong. Browsers trust the descriptor when selecting, so a wrong value skews every later choice.
Using the browser developer tools
The console tells you what was chosen. The tools below show what was transferred.
Network panel
Open the Network panel and reload the page. Filter by images (the Img filter in Chrome and Edge, Images in Firefox). For each image you can see:
- The URL, which tells you which candidate was requested.
- The transfer size, which tells you the real cost.
- The type or
Content-Type, which tells you which format arrived (avif,webp, orjpeg).
Turn on "Disable cache" while the tools are open. Otherwise, a cached larger file can hide a selection you wanted to see.
Inspecting an element
In Chrome's Elements panel, hovering over an img shows a tooltip with its rendered size, its intrinsic size, and its current source. Rendered size is what the layout produced. Intrinsic size is the file's real pixel size. If the intrinsic size is far above the rendered size multiplied by your pixel ratio, you are over-downloading.
Simulating other devices
Open the device toolbar in Chrome or Responsive Design Mode in Firefox. Both let you set the viewport size and the device pixel ratio. Test at least three setups:
- A narrow viewport at ratio 2 or 3, like a phone.
- A medium viewport at ratio 1.
- A wide viewport at ratio 2, like a high-density laptop.
Reload after each change. Selection happens at load time, and some browsers do not re-request a file when the window changes.
A repeatable debugging routine
Work through the loop in order. Most problems come from a small set of causes.
Common errors and what they look like
| Symptom | Likely cause | How to confirm |
|---|---|---|
| The largest file loads on a phone | `sizes` is missing, so it defaults to `100vw`. Or it claims a wider slot than the layout gives. | Compare `clientWidth` with the `sizes` value. |
| The JPEG loads in a modern browser | A `type` value is misspelled, such as `image/avif` written as `image/avf`. | Look at the Network type column and re-read the `type` attributes. |
| The wide crop shows on a narrow screen | A `source` with a loose `media` condition comes first in the `picture`. | Check source order. The first match wins. |
| The file is soft on a high-density display | No candidate is large enough for width times ratio. | Check that `naturalWidth` is below `neededDevicePx`. |
| Different files on two machines | The two screens have different ratios, or different zoom levels. | Print `devicePixelRatio` on each. |
| Resizing the window does not change the file | The browser reuses a larger cached candidate. | Reload with the cache disabled. |
Zoom changes the inputs
Browser zoom changes both the CSS viewport width and the device pixel ratio. At 200% zoom on a 1920-pixel-wide window, the viewport is about 960 CSS pixels wide and the ratio doubles. That means an unexpected zoom level produces an unexpected file. Reset zoom to 100% before you start testing, or at least record the zoom level next to the result.
Lazy images may not have loaded yet
A lazy image below the fold may not have been fetched when your script runs, and naturalWidth is 0 until the file arrives. Scroll to the image first, or wait for its load event.
document.querySelectorAll('img[loading="lazy"]').forEach((img) => {
if (img.complete && img.naturalWidth > 0) {
console.log('loaded:', img.currentSrc);
} else {
img.addEventListener('load', () => console.log('loaded:', img.currentSrc), { once: true });
}
});The choice is not exactly specified
The standard describes the inputs but allows the browser to decide. Two browsers can pick different candidates from the same markup, and one browser can change its behavior between versions. A good test checks that the result is reasonable, not that it matches an exact filename. Ask whether the chosen file is at least as wide as needed and not much wider.
Checking the whole page
You can also audit a page from the console. This script flags any image that is more than twice as wide as it needs to be.
window.addEventListener('load', () => {
const dpr = window.devicePixelRatio;
document.querySelectorAll('img').forEach((img) => {
const needed = img.clientWidth * dpr;
if (needed > 0 && img.naturalWidth > needed * 2) {
console.warn('Oversized:', img.currentSrc, img.naturalWidth + 'px for ' + Math.round(needed) + 'px');
}
});
});Tools like Lighthouse report the same problem under "Properly size images". Use them as a second opinion, since they test one viewport and one ratio at a time.
Exercises
Exercise
An img is displayed at 300 CSS pixels wide on a screen with a device pixel ratio of 2. Its currentSrc points to a file whose naturalWidth is 1600. What is the ratio of file width to needed pixels, and what should you check first?
Show answer
The needed width is 300 × 2 = 600 device pixels, so the ratio is 1600 ÷ 600, about 2.67. That is above 2, so the file is oversized. Check the sizes attribute first. It probably claims a wider slot than 300 CSS pixels, such as 100vw. Also check whether a candidate near 600 pixels exists.
Exercise
You resize a browser window from wide to narrow and currentSrc does not change. Give one likely reason and one way to test it.
Show answer
The browser may be reusing a larger candidate that is already in its cache, which it is allowed to do. To test it, open the developer tools, turn on "Disable cache" in the Network panel, set the narrow viewport, and reload. The currentSrc should then reflect the smaller slot.