Adding an external JavaScript file to the DOM using JavaScript
I need to load an external JavaScript file that is generated by a PHP script, I also want to pass any query string parameters to the script, I came up with the following solution:
<script>
var url = 'http://example.com/scripts/js.php?foo=bar';
url += location.search.replace(’?',’&’);
var s = document.createElement(’script’);
s.setAttribute(’type’,'text/javascript’);
s.setAttribute(’src’, url);
// get the script’s ‘outer html’ and add it to the document.
var t = document.createElement(’div’);
t.appendChild(s);
document.write(t.innerHTML);
</script>
This works in all browsers except IE (go figure), I believe the problem is that the generated script also loads more JS which seems to hang ... Is there a better way to do something like this?
UPDATE If I load the page by pressing Ctrl + F5 everything is fine ... why is that? script at http://example.com/scripts/js.php is a bunch of calls to document.write.
source to share
You can use jQuery method . It is easy to use and easy to maintain.
jQuery works for: IE 6.0+, FF 2+, Safari 3.0+, Opera 9.0+, Chrome
jQuery.getScript( url, [callback] )
Downloads and executes a local JavaScript file using an HTTP GET request. Prior to jQuery 1.2, getScript could only load scripts from the same domain as the original page. Starting with version 1.2, you can load JavaScript files from any domain. Warning. In Safari version 2 and later, it is not possible to synchronously evaluate scripts in the global context. If you're loading functions via getScript, be sure to call them after a delay.
Example:
$.getScript("test.js", function(){
alert("Script loaded and executed.");
});
source to share