Dynamically Load External Fonts
TL;DR
This text is generated by the code below. Clicking the button loads an external stylesheet that downloads and uses a new font. Give it a try:
HTML
<p id="text-to-update">
This text is generated by the code below. Clicking the button loads an
external stylesheet that downloads and uses a new font. Give it a try:
<button id="load-trigger">Download Freehand</button>
</p>
JavaScript
const kickoff = () => {
// Add the listener for button clicks
const loadButton = document.getElementById('load-trigger')
loadButton.addEventListener('click', handleClick)
}
const handleClick = () => {
// Define the font to use
const font = 'Freehand'
// Create the <link> element to get the font
const link = document.createElement('link')
link.href = `https://fonts.googleapis.com/css2?family=${font}`
link.rel = 'stylesheet'
// Grab the <head> element and append the <link> to it
const head = document.getElementsByTagName('head')[0]
head.appendChild(link)
// Grap the content to update and apply the font
const text = document.getElementById('text-to-update')
text.style.fontFamily = font
}
// Wait until the document is ready before doing stuff
document.addEventListener('DOMContentLoaded', kickoff)
Details
-
The code works by creating a new
<link>
element that calls an external font -
Once the
<link>
has been created it's added to the end of the<head>
element of the page -
The
fontFamily
is applied to the target paragraph tag -
Unless the font is already cached the
fontFamily
style is applied before the font download is likely to have finished. The browser handles this automatically and applies the style once the font is downloaded and available
References
- Dynamically load google fonts after page has loaded
Credit to this answer showing how to pull this off. The code on this page is completely based on it. - Dynamically load web font
Another answer that was linked from the first on that shows a selection box for usage - Freehand from Google Fonts
This is the font used in the example