Created
January 12, 2022 15:37
-
-
Save julianwachholz/f0e307f29c8d37a282f8e873571c4312 to your computer and use it in GitHub Desktop.
Django ServiceWorker view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// service worker | |
self.addEventListener("install", (event) => { | |
event.waitUntil( | |
caches.open("{{ cache_key }}").then((cache) => | |
cache.addAll([ | |
// {% for asset in assets %} | |
"{{ asset }}", | |
// {% endfor %} | |
]) | |
) | |
); | |
}); | |
self.addEventListener("activate", (event) => { | |
event | |
.waitUntil( | |
caches | |
.keys() | |
.then((keys) => | |
Promise.all( | |
keys | |
.filter((key) => key !== "{{ cache_key }}") | |
.map((key) => caches.delete(key)) | |
) | |
) | |
) | |
.then(() => clients.claim()); | |
}); | |
self.addEventListener("fetch", (event) => { | |
event.respondWith( | |
caches | |
.match(event.request) | |
.then((response) => response || fetch(event.request)) | |
); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def serviceworker(request): | |
"""Dumb view that renders a service worker to cache static files.""" | |
staticfiles = [ | |
"css/dist/styles.css", | |
"js/page.js", | |
"img/icon1024-maskable.png", | |
] | |
static_assets = list(map(staticfiles_storage.url, staticfiles)) | |
# Get the React bundle assets | |
loader = get_loader("DEFAULT") | |
bundle = _get_bundle(None, loader) | |
static_assets += [f"{loader.asset_path}{asset}" for asset in bundle] | |
# Calculate cache key from combined hashes | |
re_hash = re.compile(r".*?\.([0-9a-f]{8,12})\.[a-z]{2,3}") | |
hash_matches = map(re_hash.match, static_assets) | |
cache_key = "".join([match.group(1) for match in hash_matches if match]) | |
return render( | |
request, | |
"sw.js", | |
context={ | |
"assets": static_assets, | |
"cache_key": cache_key, | |
}, | |
content_type="application/javascript", | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment