Django: best practice to minify HTML to improve page speed loading - django

Its about results in https://developers.google.com/speed/pagespeed/insights/
Probably it is pretty much to just globally wrap whole HTML with spaceless template tag?
{% spaceless %}
<!DOCTYPE html>
<html>
...
</html>
{% endspaceless %}
Or it is not safe and there are some better ways?

I think there are a few options for this. After a quick search I found StripWhitespaceMiddleware and another 3rd party app called django-htmlmin. You would need to make sure that these packages are compatible with your version of python and Django. Also, have a look at the solutions in this question about HTML minification in Django.

Two three solutions I've found:
django.middleware.gzip.GZipMiddleware
http://wiki.nginx.org/HttpGzipModule
http://wiki.nginx.org/HttpStripModule
Gzip should does the same thing - removes unnecessary white spaces before html delivered.

I recommend using a custom template loader, which strips unnecessary whitespace characters. This approach has two advantages:
With the combination with cached template loader, whitespace stripping is done only once during template compilation. On the other hand with {% spaceless %} or middleware approach minification is called every time a template is rendered.
Whitespace stripping can be more aggressive - remove spaces between HTML tags, Django tags and variables.
After research, I find django-template-minifying-loader project, but it has several issues and it is unmaintained. You can use my own fork django-spaceless-templates.

You can try Jinja2, in some cases you can achieve tenfold speedup.
Check Django docs for more details.

Related

{% load staticfiles %} - Does it pre-load all recursively or on demand?

In django I'm curious concerning the {% load staticfiles %} template directive.
In static files I have a sass directory, and sass in turn can have a cache which gets quite large. I'm not inquiring of 'best practice' though, but in any case are all files pre-loaded or not?
If I'm only using, for instance, fonts, bootstrap, a personal stylesheet, etc...is it going to load all the things I'm not using?
Very curious about this. I don't want to use up more resources than needed.
You've completely misunderstood what the load tag does. All it does is make a template tag library available for the template to use: in this case, the "staticfiles" library which includes the definition of the {% static %} tag. Without that load statement, you can't use that tag.
It doesn't do anything with the staticfiles itself - indeed it can't, loading them is a matter for the browser, which will do whatever is in your HTML.

Jinja2 django 1.6 How to eliminate quotes from include tag?

Is this a bug? I have codes in template file like:
<div class="row" id="tags">
{%include 'y.html'%}
</div>
then jinja2 will render as:
But I never have any quotes in my template. And if I directly place codes in y.html in div section, this problem won't happen.
So, If I have to use include tag, How can I eliminate those annoying quotes?
EDIT:
Thanks for Daniel Roseman, the quotes only exist in Chrome tools, not in the actual html code. BUT:
If I use Chrome browser and use include tag, the layout is abnormal:
If I use Chrome browser and don't use include tag , the layout is OK:
So, there must be something wrong with jinja2 or chrome.
If it is caused by Jinja2, then how to solve this problem? Thanks.
EDIT2:
more strange things: if I move the <div class="row" id="tags"></div> into y.html, the problem will disappear even if I still use include tag.
This may be the solution, but still I don't why.
This isn't Jinja2 doing anything. This is your just your browser's developer tools. The actual HTML will be fine.

Taking all javascript from html to page-specific js file

What bit bothers me about django, is that I see in many examples that raw javascript is included in html with <script> tag. I would like to have it in independent files which are included in every page in <head> tag so that html stays clean. So that I will call something like {% add_jscript %}some js code{% endaddjsscript %} anywhere in the template to add js code. After all processing when the page is generated and it will dynamically collects all portions of added js code from processed templates and serve it as one js file.
Some app already does this or am I forced to do this on my own ?
I use django-sekizai (https://github.com/ojii/django-sekizai/) for this kind of thing. If I understand you correctly, I believe that is what you are looking for.
I know I'm a bit late to the party, but another option you could try (shameless plug) is a django app i've been working on which will allow you to inject django variables directly into external javascript files, a la Require.js
django-js-variable-injector

Play 2, how to reuse a HTML code with a tag

In Play! Framework v. 1.x there was such thing like a 'tag' where was possible to reuse some thml/template code.
In Play! Framework v 2.x, for me it is not clear still how it's going to be used (here).
For example, I want to use tag to define a header for my site (in order not to repeat myself, but just include the header every in the pages where I need it).
Could someone explain me / show how to use tags, or whatever I should use to include the header or any block of html/template code.
You showed us a sample and you are asking for sample :)
That's easy, create a common view in views.tags package (remember to leave first line empty if you're not gonna to pass any params! also remember to add brackets after tags name):
/app/views/tags/header.scala.html
<div id="header">
<h1>Hello World!</h1>
</div>
So you can 'include' it in any other view just with:
<body>
#tags.header()
Some other content
</body>

What are the pros and cons in serving CSS and JavaScript using Django template system

Often, I encounter scenarios where I see it makes sense to use template tags in CSS and JavaScript files, such as the use of {{ STATIC_URL }} in CSS to access image. I understand the only way to achieve this is to have CSS and JavaScript files served by Django. I am interested in this approach. But before I commit, I want to hear you experts' experience on it. What are the pros and cons of this approach? Thx.
Pros:
You can make a lot of per-request decisions about how things look and behave.
You can keep the number of different CSS/JS files to a minimum.
Cons:
Browsers tend to cache CSS and JS aggressively, so you'll need to use some aggressive anti-cache techniques. Of course, this means disabling caching for some/all static files.
Every CSS and JS request will consume another thread of your WSGI server. In a normal request/response cycle, each request generally takes up one thread; you're effectively tripling this, at least, so now your app that could handle 200 simultaneous requests now can only handle 66.
When your site makes it big, a CDN probably can't help you.
Alternatives:
Tweak the CSS via javascript, and set a javascript variable inside your page template to control the tweaks.
Use multiple CSS files and control their inclusion dynamically.
Generate static files as needed, but then cache them to disk and serve them via mod_xsendfile. This only works if you are serving static files from somewhere the django process can write to, such as on the same machine or a network mount.
Personally, I've been sticking with the Django team's advice to make CSS and JavaScript static files, served directly by the server instead of via Django. It hasn't been a problem and has simplified a lot of things. Generally, any time I think I need a dynamioc CSS or JS file, there's a way to refactor so I don't.
For example:
the use of {{ STATIC_URL }} in CSS to access image
I'm not sure how variable your {{ STATIC_URL }} is, but I've found that using the <base> tag in my pages fixes a lot of things. I assume this is for background images? Could you update your question to give an example?
Another thing I've done is, if my JavaScript needs dynamic data, I'll put most of the code in a JavaScript library I serve as a static file and then put the minimum dynamic stuff in a <script> tag at the end of the page. Usually I'll put it all in an object (looking a lot like JSON) and then just pass that object to a function. Come to think of it, you could just take all the dynamic stuff, make a dictionary out of it in your view function, encode it into JSON, and pass it via context. Then your page template just looks something like:
<html><head>
...
<script src="{{ STATIC_URL }}/js/foo.js"></script>
...
</head><body>
...
<script>
foo_main({{ foo_params_json|safe }});
</script>
</body></html>
This makes it a lot easier to reuse this code.