Reputation: 1981
Imagine the following two files:
test.html
<div id="stuff"></div>
<button onclick="doStuff()">Magic</button>
<script>
var foo = new function() {
this.bar = function() {
return "THE MAGIC!";
};
};
function doStuff() {
$('#stuff').load('stuffToDo.html');
}
</script>
stuffToDo.html
<div><script>document.write(foo.bar());</script></div>
I would like to insert the dynamic content from stuffToDo.html into the div in test.html. I've found that using jQuery.load() or jQuery.get() with subsequent $('#stuff').html(data) seems to cause the script to get executed before insertion and thus before it is in the scope of the foo singleton. Is there a better way to do this or at least a way to put the content into the div without executing or removing the script tags then running an eval on it?
Upvotes: 0
Views: 474
Reputation: 159
Using document.write after the document is loaded will rewrite the whole document, so if this works the entire page will be blank with the text 'THE MAGIC!', so if you don't want that to happen you will want to use jQuery to insert the data instead of document.write.
<div><script>$('body').append(foo.bar());</script></div>
Inserting a script like that can have different results on different browsers, it's better to use a script include instead. Your function foo is in the global scope, so you can use it in your included script. Use jQuery.getScript:
function doStuff() {
$.getScript('/path/to/script.js');
}
Then the script can do this:
$('#stuff').html(foo.bar());
Upvotes: 1
Reputation: 2519
I'd recommend actually inserting a script tag, then adding to innerHTML.
In plain Javascript:
var script= document.createElement('script');
script.src = stuff.js
document.body.appendChild(script);
//in script.js
var stuff=document.getElementsById('stuff');
stuff.innerHTML=foo.bar()
Upvotes: 1