Skip to content

Instantly share code, notes, and snippets.

@fatso83
Last active July 8, 2025 20:25
Show Gist options
  • Save fatso83/55fc446df3f3965ecd66e8307a5dc0e6 to your computer and use it in GitHub Desktop.
Save fatso83/55fc446df3f3965ecd66e8307a5dc0e6 to your computer and use it in GitHub Desktop.
SrcSet debug utility to print info on the currently loaded image
/**
* Use this to help determine which images are being used
* at which breakpoint. Will print lots of useful information
* on shown resolution, actual resolution, DPR and more
* Usage:
* var elems = document.querySelectorAll('.c-hero-banner__background img')
* responsiveImageDebugOutput(elems);
*
* Author: Carl-Erik Kopseng
* Source: https://gist.github.com/fatso83/55fc446df3f3965ecd66e8307a5dc0e6
*/
function responsiveImageDebugOutput(img) {
if (!img) {
throw new TypeError("Expected an image node. Got none.");
}
if(Array.isArray(img)) {
addToAllElements(img);
return;
}
if(arguments.length > 1) {
addToAllElements([].slice.apply(arguments));
return;
}
function addToAllElements(elems){
elems.forEach( function(el) {
responsiveImageDebugOutput(el);
});
}
var evalPrint = function (arg1, arg2, argN) {
var len = arguments.length;
var s = "";
while (len--) {
var arg = arguments[len];
var val = eval(arg);
if(val) {
s += '[' + arg + "=" + val + '] ';
}
}
console.log(s);
}
var listener = function () {
//Old browser
if (typeof img.currentSrc === "undefined") evalPrint('img.src');
//Modern browser
else evalPrint('img.currentSrc');
evalPrint('img.id');
evalPrint('img.width', 'img.height');
evalPrint('img.naturalWidth', 'img.naturalHeight');
evalPrint('window.devicePixelRatio');
var xDim = img.naturalWidth * window.devicePixelRatio;
var yDim = img.naturalHeight * window.devicePixelRatio;
console.log('Resolution: ' + xDim + 'x' + yDim);
};
// run the listener function if the image had already loaded
// before the listener had been set up
if (img.complete) listener();
img.addEventListener('load', listener);
}
// var elem = document.querySelector('.c-hero-banner__background img')
// responsiveImageDebugOutput(elem);
// var elems = document.querySelectorAll('.c-hero-banner__background img')
// responsiveImageDebugOutput(elems);
@timwehrmann
Copy link

Random cyberspace wanderer here. I just came across and I want to thank you for this snippet ^^

@fatso83
Copy link
Author

fatso83 commented Jun 12, 2025

Thank you! I had long since forgotten about ever writing it 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment