DEV Community

Shmilyes
Shmilyes

Posted on

How to keep the HTTP cache fresh

HTTP caching is divided into two types, but for static resources, I think most people open the mandatory cache, right?

But there is a disadvantage of forced caching that there is no way to guarantee the freshness (latest) of the resources, you can only wait for the cache time to expire to get the latest resource content

So I wrote a library Cache-Hash that specifically deals with HTTP cache busting

I've used it on my blog: https://blog.imlete.cn

Principle

By adding a hash version number to the resources introduced to the website, once the content changes, the hash will change, so that the cache can be broken by changing the url address, which ensures that the resources referenced by the website are up to date.

For example, the following form

<script src="https://demo.com/js/main.js?v=5e74b42bf5"></script>
Enter fullscreen mode Exit fullscreen mode

Usage

You can use CLI (command line tool) or JavaScript API to generate hash for references to static resources

can be installed globally using

npm install cache-hash -g

cache-hash --target source --output public

# abbreviated

cache-hash -t source -o public
Enter fullscreen mode Exit fullscreen mode

If you don't want to install it globally, you can use npx

npx cache-hash --target source --output public
Enter fullscreen mode Exit fullscreen mode

How does it work?

It reads your given target directory, detects all html, css, js in the directory, and generates an AST (Abstract Syntax Tree) for these files, and then compiles the source code back through the ast syntax tree after modifying the contents of the ast syntax tree.

Latest comments (0)