Django, recommended way to declare and solve JavaScript dependencies in blocks

和自甴很熟 提交于 2019-12-12 02:53:33

问题


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.



来源:https://stackoverflow.com/questions/19183720/django-recommended-way-to-declare-and-solve-javascript-dependencies-in-blocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!