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
- Load the basic jquery scripts in the base template (ones that are required by each template)
- Define a block for js in the base template and selectively load needed javascripts for each templates.e.g
{% block selective_js %}{% endblock selective_js %}
The above approach works well, but the only problem I see is a lot of code repetition in the templates. Say for example:
I have the following javascript files
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery.1.js"></script> <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.2.js"></script> <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.3.js"></script> <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.4.js"></script> <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.5.js"></script>
Now in more than one templates, I need all the above mentioned javascript files included and also want to initialize some of the methods within the mentioned scripts. So currently, I have to do this in all the templates:
{% block selective_js %} <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.1.js"></script> <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.2.js"></script> <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.3.js"></script> <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.4.js"></script> <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.5.js"></script> <!-- Initialize Methods --> <script type="text/javascript"> $(document).ready(function() { $('some_element').initializeScript(); }); </script> {% endblock selective_js %}
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 ?