Created
June 28, 2015 22:16
-
-
Save Snugug/219daceb11f58169ca2e to your computer and use it in GitHub Desktop.
Tiny async JavaScript font loader. Setup: Have all @font-face definitions in a `fonts.css` file, with the `.woff` file base64 encoded in. First time a user comes to your site, no custom fonts, the fonts CSS file gets downloaded async and added to `localStorage`. Each subsequent page view fonts get loaded directly from `localStorage`. I have this…
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 () { | |
'use strict'; | |
var fonts, | |
req, | |
style; | |
if (window.localStorage && document.querySelector && window.XMLHttpRequest) { | |
fonts = localStorage.getItem('fonts'); | |
if (fonts) { | |
req = document.querySelector('link[rel="stylesheet"]'); | |
style = window.document.createElement('style'); | |
style.innerHTML = fonts; | |
req.parentNode.insertBefore(style, req.nextSibling); | |
} | |
else { | |
window.addEventListener('load', function () { | |
req = new XMLHttpRequest(); | |
req.open('GET', '/css/fonts.css'); | |
req.onreadystatechange = function () { | |
localStorage.setItem('fonts', req.responseText); | |
} | |
req.send(); | |
}); | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shouldn't the beginning be the following to prevent false negative because of JS's type coercion?
It may have an exaggerated statement by the authors of object-oriented JavaScripts books over the past 4.5 years, but the checks as currently coded has always been taught to me to as the naive way of checking properties in JavaScript.