Hardware, programming and astronomy tutorials and reviews.

Managing style sheets and JavaScript files with webassets

webassets is an application that manages (compress and join) static files like JavaScript or CSS (LESS, SASS too) files. It can work with various frameworks, including Django. Everything is described in the documentation.

Compressed files have slightly smaller size and they load faster. One file made out of multiple CSS or JS files reduces the amount of HTTP requests needed to load the website. That also improves the load times.

Installation is typical - pip install webassets. If you want to use it with Django, you need to add django_assets to INSTALLED_APPS. Next you create a assets.py file in one of your applications (like the main app holding your base templates or base views). In this file we define bundles of given type files. Here is an example:

from django_assets import Bundle, register

js = Bundle('vendor/jquery-1.7.2.min.js', 'vendor/jquery.cookie.js', 'scripts.js',
            filters='jsmin', output='packed.js')
register('bundle_name', js)

Bundle takes a collection of files to bundle (each file type need their own bundle), a filter (or filters) to apply to those files and the output file with path. Every path is relative to STATIC_ROOT or static folders of your apps for dev-server. The list of filters for JS, CSS and other files (like LESS files which can be parsed to CSS) are listed in the documentation. Some of them require additional packages to be installed.

When you have your bundles defined you can use them in a template:

{% load assets %}
{% assets "bundle_name" %}
    <script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}

And that's it. In this example the whole JS code from three files got merged into one and compressed. Webassets will create a new file every time something changes in the bundled files. It will also change the version "number" added to the filename so users won't get cached old version.

If you have tests then you have to call collectstatic before starting them. Bundle will raise an exception if it can't find a file needed for the bundle. collectstatic will provide all static files (tests use debug=False so static files must be collected).

In case of style sheets you may need cssrewrite to update image paths used in those files.


Django web framework tutorials, 12 November 2012, Piotr Maliński

Comment article