Package: django-minify-html
Useminify-html, the extremely fast HTML + JS + CSS minifier, with Django.Work smarter and fasterwith my bookBoost Your Django DXwhich covers many ways to improve your development experience.RequirementsPython 3.8 to 3.12 supported.Django 3.2 to 5.0 supported.InstallationInstall withpip:python-mpipinstalldjango-minify-htmlAdd django-minify-html to yourINSTALLED_APPS:INSTALLED_APPS=[...,"django_minify_html",...,]Add the middleware:MIDDLEWARE=[...,"django_minify_html.middleware.MinifyHtmlMiddleware",...,]The middleware should bebelowany other middleware that may encode your responses, such as Django’sGZipMiddleware.
It should beaboveany that may modify your HTML, such as those ofdjango-debug-toolbarordjango-browser-reload.ReferenceFor information about what minify-html does, refer toits documentation.django_minify_html.middleware.MinifyHtmlMiddlewareThe middleware runsminify_html.minify()on the content of HTML responses.
This function minifies HTML, and any inline JavaScript and CSS.The middleware passes keyword arguments tominify()from itsminify_argsattribute, a dictionary of names to values.
These correspond to the values in the Rust library’sCfg structure, which have defaults in the Python library as visiblein the source.
By default the middleware overridesminify_cssandminify_jstoTrue.
If you need to change an argument, subclass the middleware, replaceminify_args, and use your subclass.
For example, to preserve comments after minification:fromdjango_minify_html.middlewareimportMinifyHtmlMiddlewareclassProjectMinifyHtmlMiddleware(MinifyHtmlMiddleware):minify_args=MinifyHtmlMiddleware.minify_args|{"keep_comments":True,}(This example uses Python 3.9’sdictionary merge operator.)The middleware applies to all non-streaming, non-encoded HTML responses.
You can skip it on individual views with the@no_html_minificationdecorator, documented below.To restrict it more broadly, you can use a subclass with an overridenshould_minify()method.
This method accepts therequestandresponse, and returns abool.
For example, to avoid minification of URL’s with the URL prefix/admin/:fromdjango.httpimportHttpRequest,HttpResponsefromdjango_minify_html.middlewareimportMinifyHtmlMiddlewareclassProjectMinifyHtmlMiddleware(MinifyHtmlMiddleware):defshould_minify(self,request:HttpRequest,response:HttpResponse)->bool:returnsuper().should_minify(request,response)andnotrequest.path.startswith("/admin/")Note that responses are minified even whenDEBUGisTrue.
This is recommended because HTML minification can reveal bugs in your templates, so it’s best to always work with your HTML as it will appear in production.
Minified HTML is hard to read with “View Source” - it’s best to rely on the inspector in your browser’s developer tools.django_minify_html.decorators.no_html_minificationApply this decorator to views for which you want to skip HTML minification.fromdjango.shortcutsimportrenderfromdjango_minify_html.decoratorsimportno_html_minification@no_html_minificationdefexample_view(request):returnrender(request,"problematic-template.html")MotivationHTML minification is an underappreciated techinque for web optimization.
It can yield significant savings, even on top of other tools like compression with Brotli or Gzip.There is an existing package for HTML minification in Django,django-htmlmin.
But it is much slower, since it does the minification in Python.
At time of writing, it is also unmaintained, with no release since March 2019.There are other minifiers out there, but in benchmarksminify-htmlsurpasses them all.
It’s a really well optimized and tested Rust library, and seems to be the best available HTML minifier.Some CDN’s provide automatic minification, such as CloudFlare.
This can be convenient, since it requires no application changes.
But it adds some overhead: non-minified HTML has to first be transferred to the CDN, and the CDN has to parse the response, and recombine it.
It also means that you don’t get to see the potential side effects of minification until your code is live.
Overall it should be faster and more predictable to minify within Django, at the point of HTML generation.