Opened 12 years ago
Closed 12 years ago
#18524 closed New feature (wontfix)
Create MinifyHTMLMiddleware
Reported by: | Artem Skoretskiy | Owned by: | nobody |
---|---|---|---|
Component: | Core (Other) | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | tonn81@… | Triage Stage: | Unreviewed |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
We need a simple middleware that would compactify all the pages before sending to the client. It should be basically the same as spaceless
templatetag, but for whole response.
It will reduce page size significantly -- that is important for any production site. Middleware makes sense because you don't have to care about manually using this tag in templates. It makes sense even when you use Gzip as after decompression it needs to be parsed by browser -- so size still matters.
Here is the code. Nothing special, we just use Django internals.
from django.utils.encoding import DjangoUnicodeDecodeError from django.utils.html import strip_spaces_between_tags as minify_html class MinifyHTMLMiddleware(object): def process_response(self, request, response): if 'text/html' in response['Content-Type']: try: response.content = minify_html(response.content.strip()) except DjangoUnicodeDecodeError: pass return response
The idea was taken from django-pipeline
. But since it makes sense and it only uses Django internals -- it would be great to have it in Django itself.
This can modify the semantic of the HTML. Spaces between inline elements *are* significant. (Between block elements, I believe they aren't, but I wouldn't swear it can't create layout bugs in IE.)
The implementation looks a bit specific — why only
'text/html'
? why ignoreDjangoUnicodeDecodeError
?I'd like to see a benchmark of the speed benefits: I doubt that whitespace has a noticeable impact, even on low-end hardware.
Finally this is easily implemented outside of Django.
For these four reasons, I don't think this really belongs in Django. Thanks for the suggestion, though!