This morning I’ve been watching a series of videos put out by Yahoo! regarding Javascript. While I consider myself pretty adept at Javascript these days, the first video gives you a great intro to some of the basic concepts of Javascript. For example:
No More Comments!
Placing Javascript code inside an HTML comment () was a hack developed by Netscape to work around problems in browsers that didn’t support Javascript - like Netscape 1.x. It just made sure that browsers not recognizing the
tag didn’t display the contents of any such tags they encountered (which is the normal behavior, per the HTML spec). Every browser today understands the script tag (even if Javascript is turned off). It hasn’t been needed in about 10 years, so you can stop it already…
We know what language you’re speaking!
The language="Javascript"
attribute was actually developed by Microsoft so that they could specify to a browser that the code in this tag was their Javascript-killer VBScript1. Use of the
language
attribute is deprecated and generally not needed, since Javascript is Javascript is Javascript.
SRC FTW
Something that just about everyone should know by now: It’s a bad idea to include your Javascript directly in the page2. Instead, you should put it in an external .js
file. This lets you optimize, compress, debug, validate, etc. your code much more easily.
Type Shmipe
Most people tack on type="text/javascript"
on all their tags. Unfortunately, the mime-type for Javascript wasn’t approved until earlier this year, and it’s
application/javascript
, not text/javascript
… So you’re wrong either way. Also, if you include the src
attribute like you should, the type
attribute is ignored. Instead, the browser relies on the web server to tell it the mime-type of the destination file and uses that.
Placement of Code is Very Important!
Yahoo! recommends putting your tags as low in the
as possible so that the majority of content is loaded first. It also recommends putting all your CSS
tags as high in the
as possible so that CSS styling is loaded before content.
- It was also used by Netscape so that developers could specify the exact version of Javascript their code was written for, since Netscape had a bad habit of breaking backwards compatibility when they released new versions. Unfortunately, they seem to have gotten so far off track that their implementations became more of a mess than they were worth. ↩
- Yes, there are always exceptions to every rule. Suffice it to say 99% of the time it’s a bad idea. ↩