Script Tags and how not to use them

The script tag should not be used in short-tag form. I found this out while playing with JQuery.

JQuery has underwent a lot of changes to the API as of late. Lots of useful functionality,a much simpler API, Guaranteed to be 100 times more fun than your favorite javascript / ajax library or your money back. <cf_salespitch /> While adding some functionality and refactoring, I hit a snag. All of a sudden my JQuery code stopped working. I figured I'd called something incorrectly and went poking around in the docs.

Finding nothing amiss, I started placing alerts all through my code looking for some sign of life in my Javascript.

Nothing.

Eventually I got everything happy again. It turns out I was using the script tag incorrectly. The script tag should be only used in the long form. If the short form is used, it can cause other scripts on the page to fail.

Example 1

This is an example of the short form of the script tag. The code will not alert.

view plain print about
1<script type="text/javascript" src="js/jquery-1.1.js" />
2 <script>
3 alert( 'hi' );
4 </script>

Example 2

This is an example of the long form of the script tag. This code will alert.

view plain print about
1<script type="text/javascript" src="js/jquery-1.1.js"></script>
2<script>
3 alert( 'hi' );
4</script>

I am sure I've run across this before but I didn't think of it first off. Seems since the body of the tag is empty, it shouldn't matter which form of the script tag is used. Curious, I tried a few more tests:

Example 3

This code will alert: (Note the use of the short form in the first script tag. The second tag is in long form.

view plain print about
1<script type="text/javascript" src="js/jquery-1.1.js" />
2<script type="text/javascript" src="js/tablesort.js"></script>
3<script>
4 alert( 'hi' );
5</script>

Disclaimer: I tested this code on Firefox 1.5 and IE 6.

Related Blog Entries

There are no comments for this entry.

Add Comment Subscribe to Comments