Skip to content

Instantly share code, notes, and snippets.

@iegik
Last active January 27, 2021 08:28
Show Gist options
  • Save iegik/21a38570c534b7c8f6362d4b3fbbcb89 to your computer and use it in GitHub Desktop.
Save iegik/21a38570c534b7c8f6362d4b3fbbcb89 to your computer and use it in GitHub Desktop.
Font loading technics
fetch("https://fonts.googleapis.com/css?family=Roboto:300,400,400i,500&subset=cyrillic").then(data => data.text()).then(style => Promise.all(style.match(/(?:(?:https?:\/\/))[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b(?:[-a-zA-Z0-9@:%_\+.~#?&\/=]*(\.woff2))/gim).map(url => fetch(url)), () => {document.cookie="fonts=1;path=/;domain="+location.hostname+";"}))

Loading fonts

font-display: optional;

DEPRICATED

if (getCookie('fonts') === 1) {
  printf('<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,500&subset=cyrillic">')
} else {
  printf('<script>"use strict";fetch("https://fonts.googleapis.com/css?family=Roboto:300,400,400i,500&subset=cyrillic").then(function(a){return a.text()}).then(function(a){return Promise.all(a.match(/(?:(?:https?:\/\/))[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b(?:[-a-zA-Z0-9@:%_\+.~#?&\/=]*(\.woff2))/gim).map(function(b){return fetch(b)}),function(){document.cookie="fonts=1;path=/;domain="+location.hostname+";"})});</script>')
}

Inspired by https://css-tricks.com/preventing-the-performance-hit-from-custom-fonts/


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