Skip to content

Commit 16c96ec

Browse files
vincentfretinclaude
authored andcommitted
Add cache-busting hashes to CSS/JS asset URLs
Appends ?v=<sha256> query strings to local CSS and JS URLs in generated HTML so browsers fetch fresh copies when source files change. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 902d47c commit 16c96ec

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

scripts/filters.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,27 @@
11
var urllib = require('url');
2+
var crypto = require('crypto');
3+
var fs = require('fs');
4+
var pathModule = require('path');
5+
6+
/**
7+
* Append ?v=<hash> to local CSS/JS URLs for cache-busting.
8+
*/
9+
hexo.extend.filter.register('after_render:html', function (str) {
10+
var themeSource = pathModule.join(hexo.theme_dir, 'source');
11+
return str.replace(/(href|src)="(\/(?:css|js)\/[^"]+\.(css|js))"/g, function (match, attr, url) {
12+
var relative = url.slice(1);
13+
var ext = pathModule.extname(relative);
14+
var sourcePath = ext === '.css'
15+
? pathModule.join(themeSource, relative.replace(/\.css$/, '.styl'))
16+
: pathModule.join(themeSource, relative);
17+
if (!fs.existsSync(sourcePath)) {
18+
sourcePath = pathModule.join(themeSource, relative);
19+
}
20+
if (!fs.existsSync(sourcePath)) { return match; }
21+
var hash = crypto.createHash('sha256').update(fs.readFileSync(sourcePath)).digest('hex').slice(0, 8);
22+
return attr + '="' + url + '?v=' + hash + '"';
23+
});
24+
});
225

326
/**
427
* After generating an HTML page from a Markdown file,

0 commit comments

Comments
 (0)