2

Font-face toggler bookmarklet

 3 months ago
source link: https://www.phpied.com/font-face-toggler-bookmarklet/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

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.

fonttoggleerror.png

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK