Skip to content

Instantly share code, notes, and snippets.

@gu-stav
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gu-stav/8855befcad81d6bdc376 to your computer and use it in GitHub Desktop.
Save gu-stav/8855befcad81d6bdc376 to your computer and use it in GitHub Desktop.

Fontcache

Load a JSON-File, including an encoded Font, and cache it to the browsers localStorage. To encode the font, you can use grunt-webfontjson.

Usage

  new FontCache({
    storageIndex: 'my-storage-index-v1'
  }).load( 'URL/TO/JSON-FILE' )

After it has loaded the font, it will not request the json-file anymore and instead provide the styles directly.

(function( document, window ) {
var FontCache = function( config ) {
if( !config ) {
config = {};
}
this.options = {
storageIndex: config.storageIndex || 'webfont',
jsonpCallback: config.jsonpCallback || 'webfontjsonCallback',
targetElement: config.targetElement || 'head'
};
};
/**
* Load the given JSON-File
*
* @param {String} URL to request
*/
FontCache.prototype.load = function( url, callback ) {
if( !this._supportsLocalstorage() ) {
return;
}
var _this = this;
if( this._isCached() ) {
this._applyStyles( this._getLS() )
return;
}
var ajaxOptions = {
url: url,
dataType : 'jsonp',
jsonpCallback: this.options.jsonpCallback
};
this.ajax( ajaxOptions )
.then( function( json ) {
_this._clearLS();
_this._setLS( json.css );
if( callback && typeof callback === 'function' ) {
callback( json.css );
}
});
return this;
};
FontCache.prototype.ajax = $.ajax;
/* save font to localstorage */
FontCache.prototype._setLS = function( data ) {
return localStorage.setItem( this.options.storageIndex, data );
};
/* get font from localstorage */
FontCache.prototype._getLS = function() {
return localStorage.getItem( this.options.storageIndex );
};
FontCache.prototype._clearLS = function() {
return localStorage.removeItem( this.options.storageIndex );
}
/* check if font was already cached */
FontCache.prototype._isCached = function() {
return this._getLS() ? true : false;
};
FontCache.prototype._applyStyles = function( styles ) {
var head = document.getElementsByTagName( this.options.targetElement )[0],
style = document.createElement( 'style' );
style.type = 'text/css';
style.appendChild( document.createTextNode( styles ) );
head.appendChild( style );
return this;
};
FontCache.prototype._supportsLocalstorage = function() {
return 'localStorage' in window && window[ 'localStorage' ] !== null;
};
window.FontCache = FontCache;
}( document, window ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment