Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does IE create new scope for each script tag? [duplicate]

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)

like image 440
Martin Hansen Avatar asked Aug 12 '13 12:08

Martin Hansen


2 Answers

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.

like image 198
EZLearner Avatar answered Nov 07 '22 02:11

EZLearner


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>
like image 43
Jonathan Lonowski Avatar answered Nov 07 '22 01:11

Jonathan Lonowski