Created
December 20, 2019 14:03
-
-
Save esson/b19fc6dfd60bd42da3c0cf2d4c1a5618 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
/** | |
* Preloader for Font Families. This will preload fonts used with CSS @font-face. | |
* @param fontFamilies {string[]} A collection of font family names to preload. | |
*/ | |
var preloadFontFamilies = function (fontFamilies) { | |
// Create a hidden container. | |
// | |
var containerElement = document.createElement('div'); | |
containerElement.style.opacity = 0; | |
containerElement.style.width = 0; | |
containerElement.style.height = 0; | |
containerElement.style.overflow = 'hidden'; | |
// Create an element for each font family with style property and some content | |
// and append it to the container. | |
// | |
fontFamilies.forEach(function (fontFamily) { | |
var fontFamilyElement = document.createElement('div'); | |
fontFamilyElement.style.fontFamily = fontFamily; | |
fontFamilyElement.innerText = 'x ' + fontFamily; | |
containerElement.appendChild(fontFamilyElement); | |
}); | |
// Append the container. | |
// | |
document.body.appendChild(containerElement); | |
// The browser will be triggered to download the fonts. Job done! | |
// Remove the container in the next cycle. | |
// | |
setTimeout(function () { | |
document.body.removeChild(containerElement); | |
}, 0); | |
}; | |
/** | |
* Feature detection for link[rel="preload"]. | |
*/ | |
var browserSupportsLinkPreload = ("onpreload" in document.createElement("link")); | |
// If browser doesn't support link[rel="preload"], use custom preloading. | |
// | |
if (!browserSupportsLinkPreload) { | |
var fontFamilies = [ | |
'Custom Font' | |
]; | |
preloadFontFamilies(fontFamilies); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment