I have been experimenting with AJAX recently, using it to grab snippets of HTML stored in separate files and including them in my page. For the most part, it seems to work as one would expect: the new HTML is placed on the page by a client-side script, the browser detects the change, and the site is updated to display the new data. However, I noticed this does not work with script tags... the code within the tags never run, nor are any functions detected.
For example, if I have the following HTML:
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="placeHTMLHere"></div>
</body>
</html>
and use JavaScript to set the innerHTML of the div element to the following:
<script>
var thisWillNot = function() { }
</script>
<p onclick="alert('this will work'); alert(typeof thisWillNot);">this will work</p>
I, of course, get the words "this will work" on the page, which, if I click them, alert "this will work" followed by "undefined". Thus, I know that the browser never 'executes' the function definition; any calls to thisWillNot()
fail.
I am just curious as to why I can run event-based JavaScript attached to an HTML element, but cannot add additional scripts to the page. I would have assumed it was simply that the browser did not recognize that the new scripts were added, but since it immediately rerenders the page to include the new displayable elements, I am forced to conclude that the browser does indeed know when new content (or code) is introduced to the page. Is there anything I can do to force the browser to "refresh" the JavaScript it has seen so that I can dynamically load scripts?
Thanks!