views:

87

answers:

3

Possible Duplicate:
When do I need to specify the JavaScript protocol?

for example

 <body onload="javascript:something();">

in this code, should I put javascript: ?

some of the codes attatch javascript:,

but some don't.

what is the safe and correct?

+3  A: 

No. Just use your javascript.

<body onload="something();">

javascript: can be used with the href attribute of a element.

<a href="javascript:something();">

But just for the protocol, I prefer using the onload method.

Mendy
That's not good advice. The JavaScript pseudo-protocol shouldn't be used for links either. You should attach a handler to the onclick event that returns false if you want clicking a link to execute JavaScript code.
Jimmy Cuadra
@Jimmy: It's not a "protocol", it's a "scheme". And it's not a pseudo-anything: http://tools.ietf.org/html/draft-hoehrmann-javascript-scheme-01 It's been in IE since v3 (yes, v3) and in all major browsers since.
T.J. Crowder
To be fair, an anchor point may not make sense semantically, in which case a click handler on a semantically neutral element is a better option than an <a>. However, that's not a reason to avoid the 'javascript:' scheme.
outis
Just to be clear, you dont need it, and it will be ignored.
James Westgate
JavaScript is traditionally known as a ‘pseudo-protocol’ because unlike almost every other scheme it does not represent a location, but an action to be performed on the current location. A URL that is not a locator is something that doesn't really make much sense, and indeed problems with accepting `javascript:` URLs where a locator was expected have caused innumerable security holes in the past. There are also usability problems, eg. middle-click link for new tab... oh dear, I've got an empty tab with a JavaScript error in it instead.
bobince
Now-documented in a Draft or not, `javascript:` URLs are a total disaster and should never be used in a web page. They were one of the many dreadful mistakes Netscape made when trying to attain a competitive advantage for Navigator by breaking the web in other browsers. Whilst some of those mistakes have been rectified and airbrushed out of history (eg. `<layer>`), `javascript:` hangs around like a bad smell. For anything but bookmarklets, avoid avoid avoid.
bobince
+3  A: 

A better solution would be to avoid explicit use of JavaScript in your markup altogether and to use something like jQuery to extract it all to a separate file; you can then do something like this:

$(function()
{
    // This will be run when the document is loaded.
    alert('foo');

    $('#some-link').click(function()
    {
        // This will be run when the element with id `some-link` is clicked.
        alert('bar');
    });
});
Will Vousden
+1 For separation of concerns using jQuery
James Westgate
+1  A: 

I'd suggest something like

<body>
...
<script>
function something() {}
window.onload = something;
</script>
Ms2ger