Skip to content

Instantly share code, notes, and snippets.

@gmetais
Last active June 13, 2022 22:58
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 gmetais/9dc573c607447bb57189920a1635173a to your computer and use it in GitHub Desktop.
Save gmetais/9dc573c607447bb57189920a1635173a to your computer and use it in GitHub Desktop.
A very simple an rough script that lists fonts that are loaded on a page and enumerates all elements that actually use each one. Helps discover if some fonts are loaded but barely used, so that you can skip them.
/* Simply copy and paste in the browser's console */
function weightToNumber(str) {
if (str === 'normal') {
return 400;
}
if (str === 'bold') {
return 700;
}
return parseInt(str, 10);
}
(function() {
// Detect really downloaded fonts:
document.fonts.forEach(font => {
if (font.status === 'loaded') {
console.log('Font %s %s %s was loaded', font.family, font.weight, font.variant);
const elements = [];
document.querySelectorAll('*').forEach(element => {
const computedStyle = window.getComputedStyle(element, null);
let family = computedStyle.getPropertyValue('font-family').split(',')[0].trim();
family = family.replaceAll('"', '');
family = family.replaceAll("'", '');
let weight = computedStyle.getPropertyValue('font-weight');
let variant = computedStyle.getPropertyValue('font-style');
if (family === font.family &&
weightToNumber(weight) === weightToNumber(font.weight) &&
variant === font.variant) {
elements.push(element);
}
// Todo: check if the first font is really used:
// The best way to do it seems to be checking the width of a div element
// with the font vs with the callback.
// Todo: if only 1 font-weight is declared, the browser will choose it whatever
});
console.log('All those elements use this font:');
console.log(elements);
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment