Short version: How can I keep the contents of different <script>
elements independent of each other?
Long version: I have a django template that looks a bit like this:
<div class="app-container">
<script src="app.js"></script>
<script>
$(function() {
app_init($('.app-container')); // app_init is defined in app.ja
});
</script>
</div>
The difficulty is that I want to be able to include this template multiple times in the same page. When I do this, the $('.app-container')
selector matches all of the <div class="app-container">
elements on the page.
What's the best way of keeping these independent? Some options I can think of but can't quite see how to make them work:
- Find the
<div ...>
tag that is the parent of the<script>
tag. If the script was executed automatically then I can see how this would work, usingdocument.scripts[-1]
but I can't spot how to do this when the code is executing in$(function () { ... })
. - Assign the class of the
<div>
tag programmatically, then figure out the same class programmatically in the javascript. But I can't figure out how to do this. - Something clever using anonymous functions and captures that, again, I can't quite figure out.
Edit I've seen people suggesting various variations on this:
<div class="app-container">
<script>
var thisscript = document.currentScript;
$(function() {
app_init($(thisscript).closest('.app-container'));
});
</script>
</div>
This doesn't work if the template is used multiple times in a page, as the thisscript
variable is common between them all and so it is always the last div.app-container
in the page that gets processed.