To speed up website loading, we usually need to compress JavaScript code and css code. It is time-consuming and labor-consuming to manually compress these js and css files.
Django Compressor can achieve automatic compression of js/css. Django Compressor is very easy to use and can work normally after simple settings are made according to the document. We strongly recommend that you read the entire document (the document is short ).
In use, you only need to put css/js in the compress tag Django Compressor to automatically process it. In debug mode, Django Compressor does not perform any processing. In non-debug mode, Django Compressor automatically compresses js/css files and outputs the compressed files to the STATIC_ROOT directory of django. Therefore, make sure that the STATIC_ROOT directory is correctly set.
{% Load compress %}
{% Compress <js/css> [<file/inline> [block_name] %}
<Html of inline or linked JS/CSS>
{% Endcompress %}
{% Compress css %}
<Link rel = "stylesheet" href = "/static/css/one.css" type = "text/css" charset = "UTF-8">
{% Endcompress %}
Supported coffeescript and less
In the development phase, coffeescript and less can be processed directly using js. The loading speed should be pre-compiled into js and css. Django Compressor provides COMPRESS_PRECOMPILERS settings to pre-process data based on the type.
COMPRESS_PRECOMPILERS = (
('Text/coffeescript', 'coffee -- compile -- stdio '),
('Text/less ', 'lessc {infile} {outfile }'),
('Text/x-sass ', 'sass {infile} {outfile }'),
('Text/x-scss', 'sass -- scss {infile} {outfile }'),
)
In order to use coffeescript and less in the development stage, the corresponding js file needs to be introduced in the development stage and automatically disabled in non-development environment. Unfortunately, Django Compressor does not provide relevant settings. For this reason, I wrote a tagget_setting for getting django settings in the template. This tag is included in django-helper, another project of mine.
{% Get_setting "COMPRESS_ENABLED" COMPRESS_ENABLED "%}
{% If not COMPRESS_ENABLED %}
<Script src = "{STATIC_URL} js/coffee-script.js"> </script>
{% Endif %}
Author: Tiandi yishaou