views:

838

answers:

3

Hello,

I ask because I'm running an application in which I load an external script file in the HEAD section of the page, and then attempt to call a function from it in the onLoad section of the BODY tag.

external.js

function someFunction()
{
   alert("Some message");
}

myPage.html

<html>
  <head>
    <script type="text/javascript" language="javascript" src="external.js"></script>
  </head>
  <body onLoad="someFunction();">
  </body>
</html>

Using the developer tools in IE8, I get an exception thrown at the onLoad statement because, apparently, the external javascript file hasn't been loaded yet.

I haven't had this problem come up in IE7 before, thus my question.

Did they change the load order between IE7 and IE8? If so, is there a better way to do this? (the real function references many other functions and constants, which look much better in an external file)

Thanks, B.J.

A: 

Assuming that what you think is happening is what is happening, you should try to attach the body.onLoad later on.

To simplify things, you can do it with Prototype (including prototype, of course) with

Event.observe(window, 'load', function() { myFunction.init() });

or JQuery (including JQuery) with

$(document).ready(function(){
  // Your code here...
});

I think there is a pure Javascript way to do this, but the problem is that the body element won't exist yet, so it's rough...

That said, I have had no problems running body onload in Javascript with IE8, and putting it right into the body tag, using external files. I'm going to test that right now out of curiosity, and I'll report back.

Edit: There's no problem doing the onload from an external file. However, while we're at it, you might want to get to know JQuery, Prototype or Scriptaculous :)

Yar
A: 

I doubt very much that his has changed it would break a considerable number of websites.

Try this (without using the developer tools):-

<body onload="alert(somefunction)">

this shouldn't break and will tell you whether at the point onload executes whether the identifier somefunction can be seen.

AnthonyWJones
A: 

Well, I feel pretty stupid actually.

Turns out the problem wasn't with the load order. The problem was that the external javascript file had a syntax error in one of its functions, and apparently when the exception was thrown it completely invalidated the whole file, thus making the rest of the functions unavailable to the main page.

I'm not sure if this behavior is different in IE8 compared to IE7, but anyway, that was the real problem.

Thanks for your reply.

B.J.

Benny
B.J. Maybe you didn't see the problem because when your IE8 got installed, it might have altered your IE Options (i.e. Internet Options->Advanced) and removed your check to notify you of all JavaScript errors
nickyt