A pedant that hangs out in the dark corner-cases of the web.

Monday, March 12, 2007

javascript: is not required in onclick or other event handlers

In Non-IE Browsers

The javascript: URI scheme is only necessary where URIs are used, such as href attributes.

The onevent event handlers accept javascript code, not URIs, so the scheme isn't required.

It isn't an error, because the colon causes the JavaScript parser to interpret it as a label (though MSIE just seems to ignore the leading javascript:).

In Firefox you can use the label, to confirm that it is interpreted as a label:

<a href="#" onclick="javascript:while(1) if(!confirm('Again?')) break javascript;return false;">test</a>

If you put the same code in the href, it doesn't work, because the URI parser consumes the javascript: scheme before the JavaScript processor can parse it as a label:

<a href="javascript:while(1) if(!confirm('Again?')) break javascript;return false;">test</a>


Internet Explorer supports two scripting languages (more can be installed, but are very rarely used in practice): JScript and VBScript. IE uses the first script on the page to determine the default scripting language for the page. If all of your onevent handlers are JavaScript (JScript to IE), then it makes sense to rearrange your scripts to ensure that a JavaScript appears first. Otherwise, if your handlers are a mix of JScript and VBScript, a language declaration (that looks like a label to non-IE browsers) can be used to disambiguate, e.g. onclick="javascript:alert(now Date())" or onclick="vbscript:alert(Now)".

Note that any VBScript handlers are still going to cause problems for non-IE browsers, so it may be better to define whatever VBScript code you need as a function outside the handler, using type="text/vbscript", and a dummy/alternative function with the same name can be defined for non-IE browsers using type="application/x-javascript", then call the function using a JavaScript handler. This approach also obviates the need to use these declarations.

1 comment:

Cris said...

Thanks for clearing that up. Lately I've been receiving code from third-party vendors containing constructions like 'onclick="javascript:foo()"' and it's been driving me batty. I never understood why that 'javascript:' declaration would be necessary, so I usually strip it out.

Thanks to your writeup, I see that there are reasons for doing it. Since I never have VBscript on my pages, I'll continue to strip it out :)