-
-
Save felipebn/dabbcf2ca68d13f0bb70dd54b89893f3 to your computer and use it in GitHub Desktop.
SrcSet debug utility to print info on the currently loaded image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment