使用django-compressor壓縮混淆靜態文件
使用django-compressor
壓縮混淆靜態文件
django-compressor
可以把js/css
等靜態文件壓縮,這樣有利於減少網站的請求次數,還能節省網絡帶寬。 下面介紹下如何在django
中集成django-compressor
安裝django-compressor
安裝很簡單,pip
安裝下就可以了:
pip install django-compressor
然后在'setting'的INSTALLED_APPS
中添加
INSTALLED_APPS = [
#other
'compressor'
]
setting配置
首先確保django.contrib.staticfiles
已經包含在INSTALLED_APPS
中,django1.6及以上版本是默認包含該app在其中的.
指定STATIC_URL
STATIC_ROOT = os.path.join(SITE_ROOT, 'collectedstatic')
STATIC_URL = '/static/'
STATICFILES = os.path.join(BASE_DIR, 'static')
STATIC_URL是客戶端訪問靜態資源的根路徑 配置STATICFILES_FINDERS
:
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 'blog/css/style.css' %}' type='text/css'/>
{% endcompress %}
{% compress js %}
<script type="text/javascript" src="{% static 'blog/js/jquery-3.1.1.js' %}"></script>
{% endcompress %}
分別是css和js的使用方式