I’m trying out a technique where I break my code up into individual files (so that a page that might have a bunch of different pieces is now multiple files rather than one humongous HTML page) and use ajax to load them and then set the contents as innerHTML to some parent div. This makes for very clean code and works nicely in seemingly all modern browsers, but I just noticed that when the external page contains a <script> tag, the javascript that’s in that tag is just ignored (not parsed and loaded into the parent page’s javascript context) so the methods and variables that exist in these external snippets are simply missing.
I have kludged a work around where I read the script tag’s contents in and then eval() the whole thing, and that works… however, I’m curious if I’m overlooking some more native mechanism for including the script in these external files, or if this approach is really the only one there is to achieve my goals.
TIA
This isn’t a job for
innerHTML. You should probably load the external file as a DOM object (which is the origin of theXMLHTTPRequestname) so thescripttag is turned into the proper object before getting added.A quick experiment with Firefox using jQuery (on this page, heh) shows that
innerHTMLwill add a script element that doesn’t get executed, whereas this does execute: