开发者

IE thinking object isn't loaded

I've got code that's something like the following:

<script src="library.js"></script><!-- loads window.lib and lib.subLib -->
<script>
if (!window.lib) { alert("foo") 开发者_高级运维}; //Triggers, despite library.js being loaded fine
lib.custLib = function(b) { ... }(lib.subLib); //Works fine, even though IE JUST said that window.lib wasn't loaded
</script>

And just to make things crazier, after the page is loaded, if I type

javascript:if(window.lib)alert("foo");

into the location bar, the alert fires, indicating window.lib is loaded. If instead I type

javascript:if(!window.lib)alert("foo");

the alert does NOT fire, confirming that !window.lib doesn't evaluate to true.

The only conclusion I can come to is that somehow library.js is completing execution something between when I first check if window.lib exists and when I actually use lib.subLib in the immediate invocation right after the function declaration.

EDIT: Additional information...

I've found a workaround, but first, some interesting things to note.

<script src="library.js"></script><!-- loads window.lib and lib.subLib -->
<script>
alert(!window.lib) //True
if (!window.lib) {
  alert(!window.lib) //True
}
</script>

Compare to:

<script src="library.js"></script><!-- loads window.lib and lib.subLib -->
<script>
alert(!window.lib) //False
</script>
<script>
if (!window.lib) {
  alert(!window.lib) //True
}
</script>

And the workaround:

<script src="library.js"></script><!-- loads window.lib and lib.subLib -->
<script>
var foo = !window.lib;
</script>
<script>
if (foo) {
  alert(!window.lib) //Doesn't get triggered
}
</script>

So in summation, this appears to be a bug in Internet Explorer. The workaround is to have a separate script block that set a variable to the value of !window.lib, and then to check that variable in the next script block, rather than checking !window.lib directly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜