RequireJS Shared Modules and Cache Busting with Django-Require
by Justin Michalicek on Aug. 26, 2014, 2:55 a.m. UTCI've recently been experimenting with using RequireJS in a Django environment. The biggest hurdle I ran across was cache busting and that I'm using a multi-page setup, with some shared js, and knockout with a viewmodel for handling the navbar which is on every page. Django-Require comes with two classes for managing static files, OptimizedStaticFilesStorage and OptimizedCachedStaticFilesStorage, the latter of which provides hashed filenames so that as your files change long cache times don't cause stale files to be served. The OptimizedCachedStaticFilesStorage only works when using the require template tag which comes as part of django-require.
In many cases the use of the template tag is not an issue. With the way my project using requirejs and django-require is set up, it is not ideal, though. To use it I'd have to create *-main.js files for each view, similar to this which each duplicate loading common.js (my shared, common js scripts combined into one file) and then binding the knockout viewmodel which manages the navbar and then from there they could do their truly page specific work. Right now I am able to remove the duplicate code by having my base html template load common.js as a wrapper and then bind the navbar's viewmodel. Then inside that js is a template block where each of my child templates can stick their page specific requirejs code to require and then bind their viewmodels.
To not lose that I stuck my require.config() out in the main template as well, instead of including it in common.js. Then I added a fab command as part of the deploy process which grabs the current git sha1 and adds it as a setting in a settings file which is not tracked by git. That file is imported by my main settings files. That sha1 is then appended to my STATIC_ROOT and STATIC_URL settings. My baseUrl in the require.config() in my base html template is then set based on my static url. Now when django-require runs r.js the static files are saved to a commit specific directory and served from there whether requested using a django {% static %} tag or require.js is requesting them.