Skip to content

Instantly share code, notes, and snippets.

@andy-blum
Created January 30, 2026 20:42
Show Gist options
  • Select an option

  • Save andy-blum/9cdbe6979658f74cc6a663e08d5fa1bf to your computer and use it in GitHub Desktop.

Select an option

Save andy-blum/9cdbe6979658f74cc6a663e08d5fa1bf to your computer and use it in GitHub Desktop.
(function() {
// Get the picture element (adjust selector if needed)
const picture = document.querySelector('picture');
if (!picture) {
console.log('No picture element found');
return;
}
const sources = Array.from(picture.querySelectorAll('source'));
const img = picture.querySelector('img');
const viewportWidth = window.innerWidth;
const dpr = window.devicePixelRatio || 1;
console.log(`Viewport width: ${viewportWidth}px`);
console.log(`Device pixel ratio: ${dpr}`);
console.log('---');
// Find the first matching source
let matchedSource = null;
for (const source of sources) {
const media = source.getAttribute('media');
const mediaMatches = !media || window.matchMedia(media).matches;
if (mediaMatches) {
matchedSource = source;
console.log(`✓ Matched source with media: ${media || 'none'}`);
break;
} else {
console.log(`✗ Did not match: ${media}`);
}
}
// If no source matched, use the img fallback
if (!matchedSource) {
console.log('---');
console.log(`Using fallback <img>: ${img.src}`);
return;
}
// Parse the srcset of the matched source
const srcset = matchedSource.getAttribute('srcset');
const candidates = srcset.split(',').map(candidate => {
const parts = candidate.trim().split(' ');
const url = parts[0];
const descriptor = parts[1] || '1x';
const width = descriptor.endsWith('w') ? parseInt(descriptor) : null;
const pixelDensity = descriptor.endsWith('x') ? parseFloat(descriptor) : null;
return { url, width, pixelDensity, descriptor };
});
// Calculate effective width needed (viewport * dpr)
const effectiveWidth = viewportWidth * dpr;
// Find the best candidate (smallest that's >= effective width, or largest available)
const widthCandidates = candidates.filter(c => c.width);
widthCandidates.sort((a, b) => a.width - b.width);
let selectedCandidate = widthCandidates[widthCandidates.length - 1]; // Start with largest
for (const candidate of widthCandidates) {
if (candidate.width >= effectiveWidth) {
selectedCandidate = candidate;
break;
}
}
console.log('---');
console.log(`Effective width needed: ${effectiveWidth}px (${viewportWidth}px × ${dpr})`);
console.log('---');
console.log('Available candidates:');
candidates.forEach(c => {
const marker = c === selectedCandidate ? '→' : ' ';
console.log(`${marker} ${c.descriptor.padEnd(6)} ${c.url}`);
});
console.log('---');
console.log(`🎯 SELECTED IMAGE: ${selectedCandidate.url}`);
console.log(` (${selectedCandidate.descriptor})`);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment