I am a new learner of javascript, the following code is from the javascript definitive guide.
function addEvent(elem, evtType, func)
{
if (elem && typeof(elem) == "object")
{
if (elem.addEventListener)
{
elem.addEventListener(evtType, func, false);
}
else
{
elem["on" + evtType] = func;
}
}
}
why it add
if (elem.addEventListener)
{
elem.addEventListener(evtType, func, false);
}
but the window.onload works ok under every browsers. the following is my test example.
<script type="text/javascript">
window.onload=myFuntion();
function myFuntion(){
alert("test");
}
</script>
</head>
<body>
<h1> testtste </h1>
</body>
it works ok under IE ff.
Direct assignment is not robust.
… and your code isn’t running the function on load anyway. It is running it immediately and assigning the return value (
undefined) to theonloadobject.If we fix that, then a demonstration:
The event gets overwritten. Only one function will fire.
… the example from the definitive guide isn’t very good though. It falls back to direct assignment (which makes it rather pointless) instead of trying the old proprietary APIs (e.g. attachEvent for IE 8 and lower) that would allow multiple event binding.