Skip to content

Instantly share code, notes, and snippets.

@JulienPradet
Last active December 18, 2023 11:25
Show Gist options
  • Save JulienPradet/abfbff6577ecebd3d1ffe72f6063b1f7 to your computer and use it in GitHub Desktop.
Save JulienPradet/abfbff6577ecebd3d1ffe72f6063b1f7 to your computer and use it in GitHub Desktop.
Snippet that gathers stats to easily plot the different sizes of an image based on the browser's width
// If it's the first time you're using a Snippet in Google Chrome
// 1. Open your Dev Tools
// 2. Hit "Ctrl + Alt + P"
// 3. Run the command "Create new snippet". This will open the Sources tab where you can c/c the code of this gist
// 4. Hit "Ctrl + Enter"
// 5. Go to the "Console" tab of your Dev Tools and follow the instructions displayed in the Console
//
// This snippet is inspired by https://developers.front-commerce.com/docs/2.x/advanced/production-ready/media-middleware#a-method-to-determine-image-sizes
let images = [];
let stats = new Map();
function registerCurrentImagesStats() {
stats.set(
window.innerWidth,
images.flatMap((img) => [img.clientWidth, img.clientHeight])
);
}
window.addEventListener("resize", registerCurrentImagesStats);
function copy(text) {
/* Using this trick because navigator.clipboard API does not work from snippets */
var copyFrom = document.createElement("textarea");
copyFrom.textContent = text;
document.body.appendChild(copyFrom);
copyFrom.select();
document.execCommand("copy");
document.body.removeChild(copyFrom);
}
function getImageStats() {
const lines = Array.from(stats.entries());
lines.sort(([windowWidthA], [windowWidthB]) => windowWidthA - windowWidthB);
const output = [
["Window width", images.flatMap((img, index) => [
`Width ${img.alt || `Image ${index}`}`,
`Height ${img.alt || `Image ${index}`}`,
])],
]
.concat(lines)
.map(
([windowWidth, imageWidths]) =>
`${windowWidth}\t${imageWidths.join("\t")}`
)
.join("\n");
copy(output);
console.groupCollapsed("Stats copied to clipboard");
console.log(output);
console.groupEnd();
}
function inspectImage(img) {
if (Array.isArray(img)) {
images = img;
} else if (img instanceof NodeList) {
images = [...img];
} else {
images = [img];
}
stats = new Map();
registerCurrentImagesStats();
}
console.log(
`Welcome to the image size inspector Snippet!
Usage:
1. Execute \`inspectImage(document.querySelector('img'))\` in the console by adapting the querySelector to the image you're willing to inspect
2. Resize slowly your browser to gather image information in the browser sizes you're interested in
3. Execute \`getImageStats()\` in the console: this will copy the gathered stats
4. Paste the stats in Google Sheets or any other tools you may have and create a graph from there`
);
@PofMagicfingers
Copy link

Tip: you can inspectImage($0) to use the selected node in the Elements panel.

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