Background:
I have a css and a js that is used only by the Google maps template tag, that I include in my templates where-ever needed.
Inside template tag google_map:
...
...
return render_to_string('google_map.html', context)
Inside google_map.html I have the required css and the js :
<link rel="stylesheet" type="text/css" href="mystyle.css" />
My problem is :
I have a page with 3 maps, therefore 3 calls to the template tag. This implies the css and the js is included 3 times in the same page. [Should not happen]
Now, I can-not include these css and js in the header of the page, since all the pages are not having the maps so there, on all those pages it would be a burden.
What should I do, so that if a page has 3 or more maps, even then there is only a single include of the css & js and not repeated?
I’d recommend following the pattern introduced by Paul Irish for Markup-based unobtrusive comprehensive DOM-ready execution. There’s a number of side benefits to the approach such as encapsulation, namespacing, etc., but the chief benefit for you would be conditional execution of JavaScript based on a id or class on
<body>.So in your base template change your
<body>tag to something like the following:Then, for templates that need maps just do:
That looks a little complicated, but all it’s doing is inheriting from the values any parent templates set for that block. The
ifblock is used to conditionally include the space needed between multiple classes.Finally, in your JavaScript you simply create a module for “maps” as the article describes and put all your map-specific JS there.