Include the MD5 hash in CSS URLs, so the URL changes with the CSS
authorAlex Chan <alex@alexwlchan.net>
Sun, 5 Jul 2020 17:45:30 +0000 (18:45 +0100)
committerAlex Chan <alex@alexwlchan.net>
Sun, 5 Jul 2020 17:45:30 +0000 (18:45 +0100)
Everything in /static/ is aggressively cached to improve page load and
reduce bandwidth -- but it means you need to dump the cache every time
the CSS changes or the page looks wonky.  Including the MD5 hash means
clients will reload the CSS whenever it changes.

scripts/render_html.py
templates/base.html

index 0d8ab1f..885fcce 100755 (executable)
@@ -1,6 +1,7 @@
 #!/usr/bin/env python
 
 import datetime
+import hashlib
 import itertools
 import os
 import pathlib
@@ -226,6 +227,13 @@ def create_thumbnails():
             _create_new_square(src_path, square_path)
 
 
+CSS_HASH = hashlib.md5(open('static/style.css', 'rb').read()).hexdigest()
+
+
+def css_hash(_):
+    return f"md5:{CSS_HASH}"
+
+
 def main():
     env = Environment(
         loader=FileSystemLoader("templates"),
@@ -236,6 +244,7 @@ def main():
     env.filters["render_date"] = render_date
     env.filters["smartypants"] = smartypants.smartypants
     env.filters["thumbnail_1x"] = thumbnail_1x
+    env.filters["css_hash"] = css_hash
 
     create_thumbnails()
 
index b10e1eb..48f34c6 100644 (file)
@@ -4,7 +4,7 @@
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 
-    <link rel="stylesheet" href="/static/style.css">
+    <link rel="stylesheet" href="/static/style.css?hash={{ '' | css_hash }}">
 
     {% block head_content %}{% endblock %}