Opened 7 years ago

Last modified 7 years ago

#29277 closed New feature

Add a bust_browser_cache flag to the static template tag — at Initial Version

Reported by: David Kerkeslager Owned by: nobody
Component: contrib.staticfiles Version: 2.0
Severity: Normal Keywords: browser-cache-busting static-files
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The proposal is to add a bust_browser_cache flag to the static template tag using a similar syntax to passing context variables to the include template tag. It would look something like this:

{% static 'css/style.css' with bust_browser_cache=True %}

The flag would default to False to avoid breaking existing usages of the static tag.

What flag does is add a cache_hash get parameter to the URL of the static file, with a hash of the static file. So if the content of css/style.css looks like:

p {
    color: magenta;
}

The generated URL will look like /static/css/style.css?cache_hash=0756793258f5ea00cda3e445de6bb595.

If the content of css/style.css changes to:

p {
    color: magenta;
}
p::after {
    content: "Sorry about this awful color.";
}

Then the link would be /static/css/style.css?cache_hash=c3aebd6286841ce8f4d76aa8d3eba487.

This is not a security feature, so I think it would be best to use MD5 because it is fast.

Instead, the purpose of this is to allow us to serve static files with Cache-Control: immutable or Cache-Control: max-age=<some large number> without fear. As long as the content of the file does not change, the URL's cache_hash will not change, so the browser will use the cached version. But if the content of the static file changes, the cache_hash parameter will change, causing the browser to request the new version of the file. This gets us the best of both worlds: we maximize usage of browser cache for static files, while never having to worry that our users are seeing stale versions of static files.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top