Skip to content

Instantly share code, notes, and snippets.

@satendra02
Last active March 26, 2024 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satendra02/8f85d2e2b4c3e76fbee70f17ab37bb15 to your computer and use it in GitHub Desktop.
Save satendra02/8f85d2e2b4c3e76fbee70f17ab37bb15 to your computer and use it in GitHub Desktop.
Preload google subsets font
let googleFontUrl = "https://fonts.googleapis.com/css2?family=Rubik:wght@900&family=Roboto:wght@700&family=Josefin+Sans:wght@700&family=Raleway:ital,wght@1,800&family=Inconsolata:wght@400&family=Nunito:wght@400&family=Oswald:wght@400&family=Righteous:wght@400&family=Bitter:wght@700&family=Nunito:wght@700&family=Scheherazade:wght@400&family=Noto+Sans:wght@400&family=Nova+Round:wght@400&family=Lato:wght@400&family=Noto+Sans:wght@700&family=Playfair+Display:wght@700&family=Seymour+One:wght@400&family=Arvo:wght@700&family=Poppins:wght@700&family=Lato:wght@900&family=Open+Sans:wght@400&family=Pacifico:wght@400&family=Josefin+Sans:wght@400&family=Arvo:wght@400&family=Playfair+Display:wght@400&family=Oswald:wght@700&family=Zeyada:wght@400&family=Montserrat+Alternates:wght@600&family=Poppins:wght@400&family=Ubuntu:wght@400&family=Roboto:wght@400&family=Poppins:wght@800&family=Rubik:wght@400&family=Bangers:wght@400&family=Concert+One:wght@400&family=Open+Sans:wght@700&family=Montserrat:wght@800&family=Dancing+Script:wght@400&family=Fjalla+One:wght@400&family=Ubuntu:wght@700&family=Inconsolata:wght@700&family=Bitter:wght@400&family=Contrail+One:wght@400&family=Caveat:wght@400&display=swap"
fetch(googleFontUrl).then((response) => response.text()).then((result) => {
let subsetMap = getSubsetFontMapFromFontFaceCss(result);
Object.entries(subsetMap).forEach(([subset, fontUrls])=>{
if(subset == "cyrillic"){
fontUrls.forEach((furl) => {
var link = document.createElement('link');
link.rel = 'preload';
link.href = furl;
link.as = "font";
link.type= "font/woff2";
link.crossorigin = "anonymous";
document.head.appendChild(link);
})
}
})
});
function getSubsetFontMapFromFontFaceCss(text){
const fontUrls = text.match(/\/\*[^}]*}/g);
const fontObjects = fontUrls.map(fontUrl => {
const subset = fontUrl.match(/\/\*(.*?)\*\//)[1].trim();
const url = fontUrl.match(/url\((.*?)\)/)[1];
return { subset, url };
});
const groupedFonts = fontObjects.reduce((acc, font) => {
acc[font.subset] = acc[font.subset] || [];
if(!acc[font.subset].includes(font.url)){
acc[font.subset].push(font.url);
}
return acc;
}, {});
return groupedFonts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment