Amyth
Amyth

Reputation: 32949

efficiently loading jquery and javascript files in django templates

In one of my django projects i am using lots of custom jquery scripts and lots of open source jquery plugins. Now if i load all the jquery scripts in my base template, I will be loading a lot of unused javascript code in the templates which do not require any/some of the jquery files that have been loaded which will affect the page load time of that particular template.

So, The current approach i am taking is

The above approach works well, but the only problem I see is a lot of code repetition in the templates. Say for example:

Which means there is a lot of code repetition within the templates.

Question:

How can I prevent repeating code without having to load unused javascript code in an efficient manner ?

Upvotes: 10

Views: 14177

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34563

Define a block in your parent template where you include your "default" JavaScript files and then extend the block as needed:

# base.html

{% block js %}
    <script src="{{ STATIC_URL }}js/jquery.1.js"></script>
    <script src="{{ STATIC_URL }}js/jquery.2.js"></script>
    <script src="{{ STATIC_URL }}js/jquery.3.js"></script>
    <script src="{{ STATIC_URL }}js/jquery.4.js"></script>
    <script src="{{ STATIC_URL }}js/jquery.5.js"></script>
{% endblock %}


# child.html

{% extends "base.html %}

{% block js %}
    {{ block.super }} {# includes previous content in block #}
    {# view-specific imports here #}
{% endblock %}

This will prevent repetition in your templates. Check out: template inheritance for more information about templates and inheritance.

You can use django-compressor to combine and minify CSS and JS imports and cache them for efficient loading.

Upvotes: 25

Related Questions