Beware of the greedy Script element

I've seen this problem a few times now, from a few different developers... including myself. I figure it must have plagued someone else out there too, so hopefully if you read this, if you ever encounter this problem, it wont cost you hours.

It's a hell of a problem to track down because when you run into it, it causes really strange errors. Your entire page seems to fall off the edge of a cliff. That isn't far from the truth. But you could spend hours looking at the HTML and see nothing wrong with it!

Try this -- copy this into a static HTML file and open it in IE:

 <script type="text/javascript" src="somescript.js" /> 


What do you get? This...
Hmmmm, that's funny....

Hmmmm, that's funny. Yes, I added the question mark. Not bad for free form. But notice you don't see the "Hi!!!" part.... if you still don't know why that is, I challenge you to figure it out before reading on.


... answer below ...









If this were a real page, the results would be pretty much the same, no matter what or how much content was on it. A blank page. You might even get some javascript errors thrown in too. Errors like "object expected", for an object you know for sure exists.

The problem is that the <Script> element cannot be self closing. It's interpreted as having no closing tag, and so all of the content after the script element is inside the script element -- and therefore does not appear in the visible output. It also makes dom elements that you'd normally expect to be around non-existent, which can cause errors in any script that does happen to load. So you might get a javascript error, followed by the blank page, and then assume the javascript is somehow causing the page to bomb.

Change your script tag like so, and problem solved:

<script type="text/javascript" src="somescript.js" ></script>

Appears to only be an IE thing -- works fine in FF, Safari (including for Safari Windows), and Opera.


Comments have been disabled for this content.