Script tags and Javascript Arrays in IE and Firefox

Tonight I was wrapping up a deployment for a feature that was heavily dependent on javascript. After running my first batch of tests on Firefox, everything passed without a hitch. Then I ran my tests on Internet Explorer 7 and…. nothing.. literally a blank page rendered on my screen. Thus began my latest saga of fixing compatibility issues between browsers.

The first problem was that my scripts were either being downloaded and not executing, or were not downloading at all. I checked if the javascript files were being retrieved by using program called Fiddler2. This program intercepts all HTTP requests  and responses from Internet Explorer. After running the program, it confirmed that my files were being downloaded. So, this means the files were not being executed. After staring at my html code which looked like the following:

...
<body>
<script type='text/javascript' src='/file.js' />
</body>
....

I immediately remembered that Internet Explorer doesn’t render javascript references unless you specify the complete tag. Why? I suspect its because I didn’t specify the doctype in the html tags. So to fix that problem, I changed the script tag to look like this:

...
<body>
<script type='text/javascript' src='/file.js'></script>
</body>

However, that was not the end of my javascript problems with Internet Explorer. After running the javascript, I ran into an error regarding an undefined element in an array. My first thought was that this couldn’t be. The script ran flawlessly in Firefox. After some debugging, I concluded that the Javascript engine in IE interprets text representations for arrays differently than Firefox. The evidence that lead to this conclusion came from comparing the array length returned in Firefox versus Internet Explorer. Firefox’s length was 3, while Internet Explorer’s was 4.

My Firefox-only-array looked something like this:

array = [ {id:1,name:'hi'}, {id:2, name:'hello'}, {id:3, name: 'greetings'}, ]

Turns out that last comma in the array throws off Internet Explorer and causes it to increment that length an extra tick. The fix would be to remove that last comma. The fixed code looks like this:

array = [ {id:1,name:'hi'}, {id:2, name:'hello'}, {id:3, name: 'greetings'} ]

Leave a Reply