28.Django压缩静态资源

流量是很贵的,压缩静态资源不仅可以减少带宽,很能提高访问速度。

安装django-compressor

$ pip install django-compressor

使用

setting.py中添加

INSTALLED_APPS = [
    #other
    'django.contrib.staticfiles', # 如果不存在的话
    'compressor'
]

指定STATIC_URL

setting.py中指定静态文件目录

STATIC_ROOT = os.path.join(BASE_DIR, 'static_all')
STATIC_URL = '/static/'
STATICFILES = os.path.join(BASE_DIR, 'static')

关于静态文件请阅读:https://litets.com/article/2019/4/16/351.html

配置STATICFILES_FINDERS: setting.py中

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #other
    'compressor.finders.CompressorFinder',
)

添加django-compressor配置:

COMPRESS_ENABLED = True
COMPRESS_OFFLINE = True
COMPRESS_CSS_FILTERS = [
    #creates absolute urls from relative ones
    'compressor.filters.css_default.CssAbsoluteFilter',
    #css minimizer
    'compressor.filters.cssmin.CSSMinFilter'
]
COMPRESS_JS_FILTERS = [
    'compressor.filters.jsmin.JSMinFilter'
]

模版中:

{% load compress %}
{% compress css %}
<link rel='stylesheet' href='{% static 'css/style.css' %}' type='text/css'/>
{% endcompress %}
{% compress js %}
<script type="text/javascript" src="{% static 'js/jquery-3.1.1.js' %}"></script>
{% endcompress %}

官方文档:https://django-compressor.readthedocs.io/en/stable/

声明:原创文章,版权所有,转载请注明出处,https://litets.com。