Skip to content

Instantly share code, notes, and snippets.

@Snugug
Created June 28, 2015 22:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Snugug/219daceb11f58169ca2e to your computer and use it in GitHub Desktop.
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…
(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();
});
}
}
})();
@lozandier
Copy link

Shouldn't the beginning be the following to prevent false negative because of JS's type coercion?

if ( 'localstorage' in window && `querySelector` in document && `XMLHttpRequest` in window){
  // Your current code; hasOwnProperty of course is an option, but doesn't seem critical for what you're doing.
}

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment