Files
remanso/src/utils/downloadGoogleFont.ts
Julien Calixte 78c52b0cb1 perf: ️ google font
only create link if the link doesn't exist
2024-04-06 15:40:32 +02:00

30 lines
734 B
TypeScript

import FontFaceObserver from 'fontfaceobserver'
export const downloadGoogleFont = async (font: string): Promise<void> => {
const href = assembleFontLink(font)
// check if the href already exists
const existingLink = document.querySelector(`link[href="${href}"]`)
console.log({ existingLink })
if (!existingLink) {
const link = document.createElement('link')
link.href = href
link.rel = 'stylesheet'
document.head.appendChild(link)
}
await new FontFaceObserver(font).load()
document.documentElement.style.setProperty('--font-family', font)
}
const assembleFontLink = (font: string) => {
return `https://fonts.googleapis.com/css2?display=swap&family=${font.replaceAll(
' ',
'+'
)}`
}