Javascript

A backwards compatible Script tag

When the script tag was first introduced only Netscape Navigator and Internet Explorer supported it. Other browsers hopefully ignored the contents or worse, they printed it to the screen for all the world to see. At present day, the script tag works in all major browsers like it’s supposed to. But it wasn’t always like that in the past.

For example, take the script below, nothing wrong with that, or so you would think. It worked in HTML, then it didn’t work in XHTML, and now it works again in HTML5.

<script>
function compare(a, b){
if(a < b) return a; //XHTML: it crashes on the '<' symbol
else return b;
}
</script>

Temporary solutions

Because the above doesn’t work in XHTML a solution was provided. the ‘<‘ is a reserved character in HTML, so it’s entity name has to be used: &lt;

<script>
function compare(a, b){
if(a &lt; b) return a; //HTML5 crashes here
else return b;
}
</script>

A working solution for XHTML, but it doesn’t work in HTML5 and to top it off, it’s not readable. Fortunately, they invented a different sollution:

<script><![CDATA[//HTML5 crashes here
function compare(a, b){
if(a < b) return a;
else return b;
}
]]></script>

Just add <![CDATA[]]> around your code. CDATA indicates that the text is free-form and should not be parsed. This enables you to use any reserved character you can think of without punishement. Unfortunately, it still doesn’t work in HTML5.

<script>
//<![CDATA[
function compare(a, b){
if(a < b) return a;
else return b;
}
//]]>
</script>

The above works everyware, finally a full solution. But wait what if you come against a browser that doesn’t support the script tag. (note: All modern browsers support the script tag, we’re talking about ancient browsers here).

The solution: You comment the contents of the script tag with a html comment

<script><!--
function compare(a, b){
if(a < b) return a;
else return b;
}
//-->
</script>

A backwards compatible script tag

But how about CDATA? Well, let’s just combine the two solutions into one.

<script>//<![CDATA[<!--
function compare(a, b){
if(a < b) return a;
else return b;
}
//]]>--></script>

Tadaa!, the most backwards compatible script tag you’ll ever see. enjoy!

And don’t worry about remembering this little line. You won’t need it if you use external scripts. It’s only needed for inline code.

So, the script will always work like this?

Actually, no. The script will definately work, but the ancient browser might not support the script tag or the modern browser might have turned off JavaScript.

in either case, you can and should use the <noscript> tag in the body. This will only display when scripts are not working. For example you can leave a message where the user can download your latest favorite browser which has perfect JavaScript support.

Leave a Reply

Your email address will not be published. Required fields are marked *