Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

As an answer to the question of 'How do you automatically set the focus to a textbox when a web page loads?', Espo suggests using

<body onLoad="document.getElementById('<id>').focus();">

Ben Scheirman replies (without further explanation):

Any Javascript book will tell you not to put handlers on the body element like that

Why would this be considered bad practice? In Espos answer, an 'override' problem is illustrated. Is this the only reason, or are there any other problems? Compatibility issues?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
307 views
Welcome To Ask or Share your Answers For Others

1 Answer

Using onLoad is becoming less and less common because callbacks can't be stacked using this method, i.e. new onload definitions override the old ones.

In modern frameworks like jQuery and its .load(), callbacks can be stacked and there are no conflicts when using different scripts, plugins, etc. on the same page.

Also, it is widely regarded good practice to keep the markup separate from the code, so even if one would want to use onload (which is perfectly okay if you control the complete environment and know what you're doing) one would attach that event on the scripting side either in the head or a separate javaScript file:

window.onload = function() { document.getElementById...... }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...