In one of my django projects, I use lots of custom jquery scripts and lots of open source jQuery plugins. Now, if I load all jquery scripts into a base template, I will load a lot of unused javascript code in templates that do not require any / some downloaded jquery files that will affect the page load time of this particular template.
So the current approach that I take is
- Load the main jquery scripts into the base template (the ones required for each template)
- Define the block for js in the base template and selectively load the necessary javascripts for each template .eg
{% block selective_js %}{% endblock selective_js %}
This 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 template, I need all of the above javascript files, and also you want to initialize some of the methods in the specified scripts. So for now, I have to do this in all 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> <script type="text/javascript"> $(document).ready(function() { $('some_element').initializeScript(); }); </script> {% endblock selective_js %}
This means that the templates have many code repeats.
Question:
How can I prevent code from repeating without having to efficiently load unused javascript code?
Amyth source share