Font-face toggler bookmarklet v2

October 17th, 2024. Tagged: font-face, performance

This is a different version of a font on/off toggler bookmarklet. I did one such bookmarklet earlier this year, which works by messing up font-family inside @font-face.

This new version works my messing up url() inside @font-face blocks. By "messing up" I mean changing the string "woff" to "woof" which means making the font files unavailable.

The motivation is to be able to toggle on/off and judge the "new school" of doing font fallbacks, namely using fallbacks such as local(). In short, the previous bookmarklet breaks @font-face blocks that use local(), this version does not. This version only looks for url().

Drawback: looking for "woof" files cases 404s during toggling but I think this is not a biggie.

For a demo and other info check the original post

Install

Drag this link to a bookmark toolbar near you:

Font toggle v2

Full and unminified source

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.oldSrc) {
        rule.style.src = rule.style.oldSrc;
        delete rule.style.oldSrc;
      } else {
        const src = rule.style.src;
        if (src.includes('url(')) {
            rule.style.oldSrc = src;
            rule.style.src = src.replaceAll('.woff', '.woof');
        }
      }
    }
  }  
}
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'));
}

Comments? Find me on BlueSky, Mastodon, LinkedIn, Threads, Twitter