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.

+2


source to share


4 answers


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.");
});

      

+2


source


Google way:

<script type="text/javascript">
    document.write(unescape("%3Cscript src='file.js' type='text/javascript'%3E%3C/script%3E"));
</script>

      



Instead of document.write, you can use div.innerHTML to add this line.

+1


source


Why not just add your created script tag to the head or body?

0


source


The reason it doesn't work in IE might be because you are not setting the type attribute in other script tags. IE is very picky; if two script tags are of different types, they will treat them as if they were not on the same page.

0


source







All Articles