Low bandwidth asset management in Django
Low bandwidth implies high latency - in other words, when implementing a site for low bandwidth conditions we must pay attention to the size of our assets, but also to the packaging and number of assets we include on each page.
When it comes to Django, the de-facto solution for managing assets is django-assets: it will minify and compress our assets and, crucially, allow us to merge all assets of a type into a single file.
from django_assets import Bundle, register js = Bundle('common/jquery.js', 'site/base.js', 'site/widgets.js', filters='jsmin', output='gen/packed.js') register('js_all', js)
Or in a template:
Here is a simple approach to address this problem and re-introduce the structure that we would otherwise lose:
- Include all resources statically in one (python) file,
- In the same file create a function named
require_assets. All this function does is raise an exception if the required asset is not part of the list that gets build statically;
- Code that expects or needs a particular asset, say
my_asset.css, can than invoke
require_asset('my_asset.css'). If this is missing, an exception will be raised.
This way we re-introduce the link that we have lost when we moved our list of assets to
asset.py: If I read the python code that generates a page, and I see a call to
require_asset I know which assets are expected for that page. Conversely, if I wonder why a certain asset is included, I can search the code for calls to
require_asset that include that asset. Raising an exception in
require_asset also ensures we do not forget to add our assets in
Here is an example implementation of
This is a very lightweight implementation, and there are a number of obvious improvements that could be done:
- Dependency management;
- A template tag to call
But already this simple and lightweight implementation re-introduces the semantics and structure that we had lost when moving all our asset declaration in a single place.