When Google Fonts came out last week I got really excited (even IE6 is supported!), but it brought up an old problem I’ve had with including code hosted by Google (or anyone else) in a site. Whenever the files host goes down, your sites load time can become lengthy, causing you to lose potential visitors. It’s happened a few times in the last couple months when Google services were down in our area (Search/Code/APIs), which caused a lot of our sites to ‘hang’ while loading because they were trying to download something that wasn’t available.
So I decided to implement these wonderful new fonts in a fail safe way where no site would fall victim to being crippled if/when the files were unreachable. Below are my cross-browser ways of doing just that, whether you would like to use the javascript loading method (example #1), or point directly to the css file (example #2).
The Google Fonts javascript loader method is nice because it gives you some css classes to use once the fonts have loaded, giving you more control over what your site looks like with or without the ‘fancy’ fonts, rather than merely relying on a font stack in the css to do that job.
(function() { var loaded = false; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'http://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js'; script.onload = script.onreadystatechange = function() { if ( !loaded && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { loaded = true; // Handle memory leak - IE script.onload = script.onreadystatechange = null; // check before using - IE6 if(window['WebFont']){ // Put your WebFont calls here WebFont.load({ google: { families: [ 'Yanone Kaffeesatz', 'Vollkorn' ] } }); } } }; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(script, s); })();
(function() { var head = document.getElementsByTagName("head")[0] || document.documentElement; var link = document.createElement('link'); link.type = 'text/css'; link.rel = 'stylesheet'; // enter the Google Fonts css url here link.href = 'http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz|Vollkorn'; head.insertBefore( link, head.firstChild ); })();
Both can be placed in the head or foot of your page, although I recommend placing the snippet in the head so the file(s) will begin downloading as soon as possible.
Did you find this helpful, or have ideas to make it better? Let me know in the comments!