Django, recommended way to declare and solve JavaS

2019-09-17 23:54发布

问题:

Is there a good, performant and/or recommended way to declare and provide JS dependencies for blocks in Django templates?

Basically what I want to do is this:

  1. In a Django template file containing a block, declare: I need JS library X to function.
  2. In the tag of the page, upon rendering the page, insert a script tag for this library, but never more than once.

The reasons:

  1. Minimize number of unnecessary JS libraries included in the page to keep load time acceptable in old browsers. (some libs like jquery-ui are very heavyweight for old IEs)
  2. Prevent potentially repeated loading of JS libraries, both for performance and bug-prevention reasons. This happens when you have repeated blocks or multiple blocks including the same JS lib.

I've seen some potential solutions to this but none of them were very compelling from a performance or clarity perspective, so far.

回答1:

You could use the {% include %} template tag. If you load js into the header you could do something like this:

base.html

<head>
<title>XXXX</title>
    ...
    <script type="text/javascript" src="{{ STATIC_URL}}js/jquery.js"></script>
    ...
{% block site_header %}{% endblock %}
</head>

other.html

{% extends "base.html" %}
{% block site_header %}
...
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/urlify.js"></script>
..
{% endblock %}

You will have to adjust templates/pathes/etc. to your needs.



回答2:

For this purpose, I personnaly use Django Sekizai. In my base template I have this block :

{% load sekizai_tags %}

<body>
# your own logic here

{% with_data "js-data" as javascripts %}
    {% for javascript in javascripts %}
        <script type="text/javascript" 
        src="{{ STATIC_URL }}{{ javascript }}" ></script>
    {% endfor %}
{% end_with_data %}
</body>

Then, in my included or extending templates :

{% load sekizai_tags %}

{% add_data "js-data" "myapp/js/script.js" %}

Note you can define multiple blocks, and also use it for CSS, which is very convenient.

Files added with "add_data" tag will never be repeated even if added several times.