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"></script>
</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.
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.
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....