Skip to content

Instantly share code, notes, and snippets.

@okor
Last active August 29, 2015 14:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okor/41e86dc2019075865d6a to your computer and use it in GitHub Desktop.
Save okor/41e86dc2019075865d6a to your computer and use it in GitHub Desktop.
Responsive design image efficiency stats - will display a table of results for all images and background images (ignores 0/1px tracking pixels)
// Requires jQuery and Underscore or LoDash
$ = jQuery;
function stripURLWrap(cssBackground){
return cssBackground.replace(/^url/g,'').replace(/\(|\)/g, '')
}
function getPercentage(number) {
return Math.floor((Math.round( number * 10 ) / 10) * 100) + '%';
}
var imageStats = [];
_.each( $('*'), function(node){
var $node = $(node);
var hasImage = $node.attr("src") || $node.css('backgroundImage');
if (!hasImage) return;
var imageURL = $node.attr("src") || stripURLWrap($node.css('backgroundImage'));
var imageUrlIsValid = imageURL.toLowerCase().split('?')[0].match(/\.jpg|\.png|\.gif/)
if (!imageUrlIsValid) return;
var nodeImage = new Image();
nodeImage.src = imageURL;
// images with a src width less than 1 are probably tracking pixels
// so we want to ignore them.
if (nodeImage.width > 1 || nodeImage.height > 1) {
imageStats.push({
efficiency: getPercentage( ($node.outerWidth() / nodeImage.width) ) + " / " + getPercentage( ($node.outerHeight() / nodeImage.height) ),
displaySize: $node.outerWidth() + " x " + $node.outerHeight(),
srcSize: nodeImage.width + " x " + nodeImage.height,
srcURL: imageURL,
node: node
})
}
});
console.table(imageStats);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment