Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active July 14, 2020 20:29
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 james2doyle/8e53e6c1a8ef0c0f9796ed3039b18e97 to your computer and use it in GitHub Desktop.
Save james2doyle/8e53e6c1a8ef0c0f9796ed3039b18e97 to your computer and use it in GitHub Desktop.
A cache-busting pattern based on a version file. Checks to see if an hour has passed before clearing or reseeding
// <meta name="build-version" content="build-12345" />
// window.localStorage.setItem('cacheTime', '{{ date("%H") }}');
const CACHE_TIME = Number(window.localStorage.getItem('cacheTime') || '0');
const CURRENT_TIME = (new Date).getHours();
/**
* The path to fetch the version text file from
*
* @type {String|null} VERSION_PATH
*/
const VERSION_PATH = document.querySelector('meta[name="build-version"]')
? document.querySelector('meta[name="build-version"]').getAttribute('content')
: null;
if (VERSION_PATH === null) {
console.warn('Cache: no version meta tag found. Cache busting may not work correctly');
}
/**
* Store the "old" version as it will get updated if required
*
* @type {String|null} PREVIOUS_VERSION
*/
const PREVIOUS_VERSION = window.localStorage.getItem('currentVersion') || null;
const cacheBuster = async () => {
try {
const currentVersion = await (await fetch(VERSION_PATH)).text();
// same version and same hour - dont bother busting
if (currentVersion === PREVIOUS_VERSION && CACHE_TIME === CURRENT_TIME) {
return;
}
// might as well update the version
window.localStorage.setItem('currentVersion', currentVersion);
// figure out why we busted the cache just in case we need to debug later
const reason = CACHE_TIME !== CURRENT_TIME ? 'time' : 'version';
// seed the cache or delete it to be reseeded via other code
(new Promise(r => r()))
.then(() => {
console.warn('Cache: busted for stale', reason);
});
} catch (e) {
console.error('Cache:', e);
return;
}
};
/**
* import cacheBuster from 'Functions/cache-buster';
* cacheBuster()
* .then(doSomethingWithCachedData);
*/
export default cacheBuster;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment