Why is the following html file showing title as default in IE? The other browsers show title as mytitle.
<script>
window.mylib = window.mylib || {};
mylib.title = 'mytitle';
</script>
<script>
var mylib = mylib || {};
document.title = mylib.title || 'default';
</script>
Does IE create a separate scope for each of the script tags?
And is that just a bug or why does the behavior differ?
(tested in IE8 and latest chrome/ff/opera)
HTML <script>
tags Javascript are executed in the scope of the window
. Thus, separated script tags are executed on the same scope.
Specifically with IE7, try not re-defining the variable on the second time:
Instead of
var mylib = mylib || {};
use
mylib = window.mylib || {};
IE7 probably overwrites the definition of mylib
when var mylib
is encountered.
Scope shouldn't be an issue. Each <script>
should be evaluated within the same global scope.
However, window.mylib = ...
doesn't appear to be considered an actual declaration in IE8. So, following it with a var mylib
causes an override / reset to undefined
.
<script>
window.mylib = {};
</script>
<script>
console.log(typeof window.mylib); // object
</script>
<script>
var mylib;
console.log(typeof window.mylib); // undefined
</script>
It should work as expected when using either var mylib
or window.mylib
throughout. Seems it's just the mixture that's the problem.
<script>
var mylib = mylib || {};
mylib.title = 'mytitle';
</script>
<script>
var mylib = mylib || {};
document.title = mylib.title || 'default'; // 'mytitle'
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With