Steve
Steve

Reputation: 21

Adding external JavaScript file into DOM via 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 as well, 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 downloads 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 works fine...why is this? The script at http://example.com/scripts/js.php are a bunch of document.write calls.

Upvotes: 2

Views: 1131

Answers (4)

Jarett Millard
Jarett Millard

Reputation: 5948

The reason it's not working in IE might be because you're not setting the type attribute in the other script tags. IE is very picky; if two script tags have different types, it will treat them as though they're not even on the same page.

Upvotes: 0

Anatoliy
Anatoliy

Reputation: 30073

Google's 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 may use div.innerHTML to append this string.

Upvotes: 1

Pointy
Pointy

Reputation: 413682

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

Upvotes: 0

jantimon
jantimon

Reputation: 38142

You might use the jQuery method. It is easy to use and easy to maintain.

jQuery is works for: IE 6.0+, FF 2+, Safari 3.0+, Opera 9.0+, Chrome

jQuery.getScript( url, [callback] ) 

Loads, and executes, a local JavaScript file using an HTTP GET request. Before jQuery 1.2, getScript was only able to load scripts from the same domain as the original page. As of 1.2, you can now load JavaScript files from any domain. Warning: In Safari version 2 and older it's not possible to evaluate scripts in a global context synchronously. If you load functions via getScript, make sure to call them after a delay.

Example:

$.getScript("test.js", function(){
  alert("Script loaded and executed.");
});

Upvotes: 2

Related Questions