-
I might be missing something obvious, as I can't find much about this topic in terms of discussions, but I can't really figure out how to process content assets (images linked from a blog post, for example, as opposed to CSS and JS) to add an hash to the filename of the path, based on the content file, for cache-busting purposes. Is there any best practice I should follow when trying to do that? For a documentation website, like the one I'm building, this is crucial, as documentation images or resources (e.g. PDF) might get updated, but not renamed, so a cache-busting technique is fundamental for consistent, robust, and reliable content. Any suggestion on the direction to take would be greatly appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I use code like this: crc32 algorithm // CRC32 code based on https://stackoverflow.com/a/18639999/387194
const crcTable = (() => {
let c;
const result = [];
for (let n =0; n < 256; n++) {
c = n;
for(var k =0; k < 8; k++) {
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
result[n] = c;
}
return result;
})();
const crc32 = (str) => {
let crc = 0 ^ (-1);
for (let i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF];
}
return (crc ^ (-1)) >>> 0;
};
module.exports = (str) => {
return crc32(str).toString(36);
}; and in eleventy config const crc32 = require('./crc32');
const fs = require('fs/promises');
module.exports = function(eleventyConfig) {
eleventyConfig.addPassthroughCopy({ "static": "." });
eleventyConfig.addAsyncShortcode('with_hash', async function(filename) {
const content = await fs.readFile(`./static/${filename}`, 'utf8');
const hash = crc32(content);
return `${filename}?${hash}`;
});
}; and inside template I use: <link rel="stylesheet" href="/{% with_hash "css/blog.css" %}"/> The same would be with any asset like image or PDF. And good thing about CRC32 encoded with Base 36 is that the hash is small unlike MD5.
|
Beta Was this translation helpful? Give feedback.
I use code like this:
crc32 algorithm
and in eleventy config