Last active
August 29, 2015 14:09
-
-
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)
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
// 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