Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure that a javascript file is included only once in Django

I have a few child templates which have extraheads which include the jquery script. Sometimes they are used together. How can I have the jquery javascript file loaded only once? If it were convenient to set template variables, I could set and check one before including the line.

like image 586
Mitch Avatar asked Dec 20 '25 02:12

Mitch


2 Answers

My advice: Just include jQuery on your base's <head> and call it a day. Saves you from having to worry if a child template uses jQuery or not and it is just a 19kb download on the first page load and that's it. If you use Google's API cloud, it may not even be any as the user might have it cached from another site.

This may not work for you, but I advice you to consider it if possible.

like image 196
Paolo Bergantino Avatar answered Dec 24 '25 12:12

Paolo Bergantino


My usual approach to this problem is to either wrap all of my child templates in one template that takes care of my includes (JS and CSS). I then make sure my caching is set properly, so that these scripts are only downloaded once per user. In other words, I force the download of all my external scripts on the first view, then rely on caching to not redownload the JS each time.

Combining all of your JS into one file will also improve download time due to the reduction in requests that will be generated.

Another thing to note is that you mentioned putting the JS in heads. While most people do this, placing JS in the head can make your pages appear to load slower. JS files are not downloaded in parallel, so they block all other downloads. Google and Yahoo recommend placing JS at the bottom of your page where possible to improve the user experience.

See the Yahoo YSlow tool and the Google PageSpeed tool for this.

like image 40
Dan Lorenc Avatar answered Dec 24 '25 10:12

Dan Lorenc