Skip to content

Instantly share code, notes, and snippets.

@Inkdpixels
Last active August 29, 2015 14:08
Show Gist options
  • Save Inkdpixels/8f37f8687d2b24e98950 to your computer and use it in GitHub Desktop.
Save Inkdpixels/8f37f8687d2b24e98950 to your computer and use it in GitHub Desktop.
webfontjson-localStorage.js
<script type="text/javascript">
/**
* Load and cache the css string from webfontjson(https://github.com/ahume/webfontjson) in the UA's localStorage.
* @author Tyll Weiß(https://github.com/Inkdpixels)
* @param url {string} The URL where the JSONP is located.
* @param jsonpCallbackName {string} The name of the function which will be called by the JSONP.
* @param useDefaultCallback {boolean} Use the default callback provided by this script?
* @param timestamp {string} The timestamp, to clear the users cache - change this string.
*/
var loadCachedWebFonts = function(url, timestamp, jsonpCallbackName, useDefaultCallback) {
jsonpCallbackName = jsonpCallbackName || 'webFontJsonCallback';
useDefaultCallback = useDefaultCallback || true;
// Prevent from running this function if localstorage isn't support (Fallback system fonts will be used).
if(!window.localStorage || !url || !timestamp) {
return;
}
var headEl = document.getElementsByTagName('head')[0],
jsonpCallback = function(res) {
var css = res.css;
// Create the localStorage cache.
localStorage.webfonts = css;
// Attach the css to the UA's document.
attachStyles(css);
// Make sure the global var is removed.
if(useDefaultCallback) {
window[jsonpCallbackName] = undefined;
}
},
attachStyles = function(css) {
var style = document.createElement('style');
// Setup the style element.
style.type = 'text/css';
style.appendChild(document.createTextNode(css));
// Append the element to the UA's <head>.
headEl.appendChild(style);
},
loadJSONP = function(url, callback, context) {
// Create script
var script = document.createElement('script');
// Setup the script element.
script.type = 'text/javascript';
script.src = url;
// Load the JSONP.
headEl.appendChild(script);
// Remove the temporary script element.
headEl.removeChild(script);
};
if(localStorage.webFontStorageTimestamp === timestamp && localStorage.webfonts) {
// If the passed timestamp matches the localStorage timestamp, attach the css from the users localStorage.
attachStyles(localStorage.webfonts);
} else {
// If the timestamp does NOT match, (re-)load and run the JSONP callback.
// Renew the timestamp.
localStorage.webFontStorageTimestamp = timestamp;
// Load the JSONP and run the callback.
loadJSONP(url);
// Make sure the callback is accessible for the JSONP.
if(useDefaultCallback) {
window[jsonpCallbackName] = jsonpCallback;
}
}
}('MyGeneratedJsonFile.woff.json', '?t=22102014', 'jsonpCallBackName', true);
// Make sure the global var is removed after running it.
loadCachedWebFonts = undefined;
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment