Skip to content

Instantly share code, notes, and snippets.

@JohnRSim
Last active June 28, 2023 16:11
Show Gist options
  • Save JohnRSim/924457e5313bff1b8722dda8ac682da2 to your computer and use it in GitHub Desktop.
Save JohnRSim/924457e5313bff1b8722dda8ac682da2 to your computer and use it in GitHub Desktop.
Example of applying CDN Cache Busting support for OCM Images
/**
* Cachebusting value based on update date from OCM Asset to reset the cache
*/
function cb(asset) {
const time = new Date(asset.updatedDate.value).getTime()
return parseInt(time, 10).toString(36)
}
/**
* Retrieve the sourceset for an asset that is constructed from the rendition
*
* @param {asset} client - the asset whose fields contain the various renditions
* @returns {Object} - An Object containing the the sourceset as well as individual rendition
* url that can be used as default src
*/
function getSourceSet(asset) {
const urls = {};
urls.srcset = '';
urls.jpgSrcset = '';
if (asset.fields && asset.fields.renditions) {
asset.fields.renditions.forEach((rendition) => {
addRendition(urls, rendition, 'jpg');
addRendition(urls, rendition, 'webp');
});
}
//return asset updated timestamp
const cbVal = cb(asset);
// add the native rendition to the srcset as well
urls.srcset += `${asset.fields.native.links[0].href}?cb=${cbVal} ${asset.fields.metadata.width}w`;
urls.native = asset.fields.native.links[0].href;
urls.width = asset.fields.metadata.width;
urls.height = asset.fields.metadata.height;
return urls;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment