mozboz
mozboz

Reputation: 1108

IE fails, when calling functions from external javascript?

I have a piece of code that can be simplified to this:

var s='' ; 

s += "<"+"script type=\"text/javascript\" src=\"http://somehost.com/scripts/FooFunctions.js\">\n";
s += "<"+"/script>" ;
s += "<"+"script type=\"text/javascript\">\n";
s += "FooFunction(42, 'i love cats');\n";
s += "<"+"/script>" ;

document.write(s) ; 

In all browsers except IE, this executes as you'd expect - functions from somehost.com/scripts/FooFunctions.js work as expected.

In Internet Explorer, this fails.

Googling this seems difficult. I've found the occasional post witht the same problem, but no solution.

(There is a valid reason that the external file needs to be included from javascript this way, and that the pgae can not have a <script src="http://somehost.com/scripts/FooFunctions.js"> inserted in it.)

To be clear, the question is: How can I make the above piece of code function the same in Internet Explorer as it does in e.g. FireFox?

Upvotes: 2

Views: 4172

Answers (3)

Aaron Bassett
Aaron Bassett

Reputation:

As soon as the document.write call is complete it will run the function in the second script tag. Regardless of whether or not the external script has loaded yet. This should not just be an IE problem but should effect all browsers. Are you sure that it is not effecting other browsers as they have the external script cached? What happens when you clear your cache and try again in another browser?

Anyways, in an ideal world you should just be able to use .onload on the script tag but I'm 99% sure that there is problems with onload not firing on script tags in IE6 so we need to resort to using onload on the window element instead. This will event will not fire until all scripts have been downloaded including external js files like above.

Upvotes: 0

Yisroel
Yisroel

Reputation: 8174

It looks like IE is calling FooFunction before the script is loaded. You can test this by using setTimeout("FooFunction(42, 'i love cats')", 1000); assuming one second is enough time for the script to load, this call will succeed.

If you can't use a framework like jQuery to load the scripts, which will provide you with a callback when the script loads, you might be able to hack your own with setInterval, checking for FooFunction

Upvotes: 0

IAdapter
IAdapter

Reputation: 64717

Try this, it works in IE


function addJsFile(jsFileLocation){
    var script=document.createElement('script');
    script.type='text/javascript'; 
    script.src=jsFileLocation; 
    document.getElementsByTagName("head")[0].appendChild(script);
}
addJsFile("http://code.jquery.com/jquery-latest.pack.js");
setTimeout(function(){alert(jQuery);},1000);

Upvotes: 2

Related Questions