Font-face toggler bookmarklet

January 8th, 2024. Tagged: font-face, performance

Ever wanted to look at your page and turn Web Fonts on and off? Experience the layout shift repeatedly, like some sort of UX torture? Look no further, here comes the handy bookmarklet.

Install

Drag this link to a bookmark toolbar near you:

toggle fonts

Use

Go to a page with web fonts and click to toggle. Like so:

Source

The idea is you go through all stylesheets and mess with the fontFamily of @font-face rules. Simple. Stash them as fontFamiliar for ease of toggling back.

const errors = [];
for (let s = 0; s < document.styleSheets.length; s++) {
  let rules = [];
  try {
    rules = document.styleSheets.item(s).rules;
  } catch (_) {
    errors.push(s);
  }
	
  for (let i = 0; i < rules.length; i++) {
    const rule = rules.item(i);
    if (rule.constructor.name === 'CSSFontFaceRule') {
      if (rule.style.fontFamiliar) {
        rule.style.fontFamily = rule.style.fontFamiliar;
        delete rule.style.fontFamiliar;
      } else {
        rule.style.fontFamiliar = rule.style.fontFamily;
        rule.style.fontFamily = '';
      }
    }
  }  
}
if (errors.length && !window.__fontfacetogglererror) {
  window.__fontfacetogglererror = true;
  const msg = ['Could not access these stylesheets:'];
  errors.forEach(idx => msg.push(document.styleSheets.item(idx).href));
  alert(msg.join('\n\n'));
}

Limitations

When the stylesheets are not accessible by document.styleSheets API (e.g. on a third party domain, what!?), we cannot mess with them. But we can report their URLs nonetheless. Only the first time though, too much otherwise.

Layout shift helper

Want a layout shift monitor to go with your toggle? Paste this into the console before you go toggling:

new PerformanceObserver((list) => {
  let cls = 0;
  for (const entry of list.getEntries()) {
    cls += entry.value;
  }
  console.log(cls);
}).observe({type: 'layout-shift'});

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov