The proper way to include Javascript in your (X)HTML page +

It’s 2008. The type attribute is useless and ignored in presence of a src attribute. There’s no better time than now to start including <script>s on your pages the right way. And that is:

<script src="http://some.server.address/path/to/your/jsfile.js"></script>

That’s all there is to it. Remember to place those at the end of your document structure, just before the closing </body> tag, it’s faster that way.

3 Responses to “The proper way to include Javascript in your (X)HTML page”

  1. It’s 2008. XHTML became a W3C recommendation 8 years ago, which was just enough time for anyone to check the spec and see that the type attribute really is required. It is so in XHTML 1.0 both Transitional and Strict, and it was so in HTML 4.

  2. While it is true the w3c recommendations currently state it’s required, the current implementations (for all practical use cases) are essentially ignoring it.
    The fact that the xhtml recommendations date back to 2002 (xhtml) and 1999 (html 4) ain’t helping much either.

    Another thing is that the text/javascript “mime-type” (media type?) has been proposed for obsoletion (according to RFC 4329),
    and the HTML 5 working draft says that mime-types should be defined with accordance to RFC 2046 which is a bit ambiguous about whether to use text/something or application/something. But that’ll be sorted out hopefully.

    What “hit the nail on the type coffin” for me was reading the current working draft for HTML 5 and seeing this: http://www.w3.org/TR/2008/WD-html5-20080122/#the-scripts
    Step 1. clearly states that the default is javascript.
    They’re doing it like that because all the browser vendors already have it implemented that way. Which makes my code in the post work flawlessly and even future-proof so far :)

    BTW, I find it amusing that the same document lists ECMAscript as the supported scripting language’s name, and yet they’re still using text/javascript as the mime-type attribute…

    Validation and standards are nice to have. But they’re not the “highest of all causes”. And they’re sometimes downright impossible to achieve while still giving the client (or the boss, or whatever) what he reasonably wants (that can very well be the topic of a whole different article). Pragmatists just sleep better :)

  3. Yeah, the whole mime-type thing with JavaScript blows. That’s why we’re forced to use this “beautiful” regexp in Prototype lib: contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)