views:

160

answers:

2

Aren't Javascript blocks supposed to execute in the order that they are placed on the page?

IE6 doesn't seem to follow that rule in some situations. My page basically looks like this:

<html>
<head>
    <title>Widget Sandbox</title>
    <script type="text/javascript" src="http://domain2.com/script.js"&gt;&lt;/script&gt;
</head>
<body>
    <script type="text/javascript">
        myObj.doSomething();
    </script>
</body>
</html>

This page is hosted on one domain, while the script at the top is hosted on a second domain. The myObj object is defined in the external script and used in the local script block. Every once in a while, the script block in the <body> is executing before the script referenced in the <head>.

The issue is difficult to reproduce. I usually have better luck if I duplicate the above page and add a link to the duplicate, and vice-versa, and click the links until I get an error.

The error would be "myObj undefined" followed by the line number.

Anyone have an idea of what I could be doing wrong? This only happens in IE6. The script works perfectly in IE6 95% of the time otherwise.

A: 

The most likely explanation is that the first script is sometimes failing to load, due to something like the connection being dropped by the server, the server returning a 503 Service Unavailable error, or some similar reason.

Try running an HTTP debugger like Fiddler; then, when the error occurs, you can examine the HTTP request/response cycle to see what the problem was.

NickFitz
I've already done exactly that. The script reference does not fail to load when this issue happens.
Freyday
+2  A: 

i once had a problem very similar to the one you describe.

It happened only with a specific version of IE6. The JS was being gzipped by the web server and IE 6 executed my script before the JS, after it's been downloaded but before it's been unzipped... very strange....

it solved when i disabled gzip in my apache for IE6 requests. (don't know if you can do that) The alternative is to set a timer to check if MyObj is defined....

zeky
Interesting. We are gzipping the content of the script. I'll give it a shot and let you know my results.
Freyday
It solved the issue! Thanks much!
Freyday
Glad it worked. it took me a lot of time to figure it out... couldn't find docs or reports of it anywhere.
zeky