Reputation: 3756
I have a django generated page, and in it I have a jQuery on click handler that loads another django page using the jQuery load() function:
$("#loadit").on("click", function() {
load_it($("#loadit"), url);
});
function load_it(el, url)
{
var el_wf = $('<div />');
el_wf.load(url, function (html, status) {
el.children().remove();
el_wf.show();
el_wf.appendTo(el);
});
}
In that second django template I have some code like this:
<script type="text/javascript" src="/static/scripts/myscript.js"></script>
.
.
.
<div>
<script>
function_in_myscript();
</script>
</div>
When I click on the element in the first page, and the second page is loaded that js function is not invoked. There are no errors, and the rest of the template is run and the page is generated.
But if I go to the second URL directly from my browser the js function is run.
Is there something with load() that is preventing this from working?
Upvotes: 0
Views: 400
Reputation: 671
JavaScript inserted as DOM text will not execute. The W3C Specification for XMLHttpRequest states: Scripts in the resulting document tree will not be executed, resources referenced will not be loaded and no associated XSLT will be applied.
The solution is to call JavaScript’s eval() function on the text of the script. Using jQuery it is very easy to iterate through the collection of script tags and to eval() contents of the TextNode. However this looks like a bad practice.
Using script tag in second html is not a good way of loading a new js file. I suggest that you use RequireJS for this purpose. RequireJS takes a different approach to script loading than traditional tags. It can run fast and optimize well.
Here is an example to demonstrate the usage, In first File:
<script type="text/javascript" src="/static/scripts/require.js"></script>
.
.
.
<script type="text/javascript">
require.config({
paths: {
myscript: '/static/scripts/myscript'
}
});
$("#loadit").on("click", function() {
load_it($("#loadit"), url);
});
function load_it(el, url)
{
var el_wf = $('<div />');
el_wf.load(url, function (html, status) {
el.children().remove();
el_wf.show();
el_wf.appendTo(el);
require(['myscript'], function(myscript) {
function_in_myscript();
});
});
}
</script>
In that second django template just load the html code. No need for loading script.
Upvotes: 3