You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
28 lines
773 B
28 lines
773 B
interface FontOptions {
|
|
family: string
|
|
weight?: number
|
|
}
|
|
|
|
const loadedFamilies = new Set<string>()
|
|
|
|
export function useGoogleFont(fonts: FontOptions[]) {
|
|
const families = fonts.map((f) => {
|
|
const w = f.weight ? `:wght@${f.weight}` : ''
|
|
return `family=${encodeURIComponent(f.family)}${w}`
|
|
})
|
|
|
|
const link = document.createElement('link')
|
|
link.rel = 'stylesheet'
|
|
link.href = `https://fonts.googleapis.com/css2?${families.join('&')}&display=swap`
|
|
|
|
const pending = fonts
|
|
.filter((f) => !loadedFamilies.has(f.family))
|
|
.map((f) => document.fonts.load(`${f.weight || 400} 1em ${f.family}`))
|
|
|
|
if (pending.length > 0) {
|
|
document.head.appendChild(link)
|
|
for (const f of fonts) loadedFamilies.add(f.family)
|
|
}
|
|
|
|
return Promise.all(pending)
|
|
}
|
|
|