views:

401

answers:

5

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.

A: 

You could define separate blocks for your script and for other extraheads in base template. In base template leave block for your script blank. Fill it with link to a file when needed in templates which are extending base.

Mike Korobov
+3  A: 

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.

Dan Lorenc
+8  A: 

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.

Paolo Bergantino
+2  A: 

I'd mostly bite the bullet and load jQuery with every template. But if you really really really have to have this feature, then I'd recommend a custom template tag. Check out the docs, especially the part about setting a variable in the context.

Antti Rasinen
A: 

You could pass all required files as a context variable and then write a template tag that removed duplicates and loaded what was left.

You could control load order this way also.

andybak