|
(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 )); |