Site Navigation

Tuesday, September 25, 2007

bug 162 - global namespace pollution in IE

Issue: #162
Affects: IE5, IE5.5, IE6, IE7

Every element on a page in IE with an ID or a NAME creates (cough, pollutes!) the global JavaScript namespace. Not only is this bad practice, but it is highly prone to errors down the road.

Example:

<div id="myfoo"></div>
<div id="mybar"></div>
.
.
.
<script type="text/javascript">
myfooStr = 'Hello World';
myfoo = document.getElementById('myfoo');
myfoo.innerHTML = myfooStr;
</script>


In IE, the above code will cause errors... in any other browser it will simply set the content of the div to "Hello World". Why an error? Well since IE creates a global variable in the JavaScript namespace for each element on the page, with an ID, before the script even executes, myfoo is already defined. In the script, attempting to reference it to something (even in this case the same element), IE throws a script error.


Known Workarounds: One. Watch the scope of variables. (e.g. use 'var', inside functions to keep the scope local)

Example Workaround Code:

<div id="myfoo"></div>
<div id="mybar"></div>
.
.
.
<script type="text/javascript">
function doStuff(){
var myfooStr = 'Hello World';
var myfoo = document.getElementById('myfoo');
myfoo.innerHTML = myfooStr;
}
</script>



Related Issues: None.