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

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

javascript - window.onload vs <body onload =“”/>(window.onload vs <body onload=“”/>)

What exactly is the difference between the window.onload event and the onload event of the body tag?

(window.onload事件和body标签的onload事件之间究竟有什么区别?)

when do I use which and how should it be done correctly?

(我何时使用哪个以及如何正确使用?)

  ask by Manu translate from so

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

1 Answer

0 votes
by (71.8m points)

window.onload = myOnloadFunc and <body onload="myOnloadFunc();"> are different ways of using the same event .

(window.onload = myOnloadFunc<body onload="myOnloadFunc();">是使用同一事件的不同方式。)

Using window.onload is less obtrusive though - it takes your JavaScript out of the HTML.

(使用window.onload虽然不那么突兀 - 它会将你的JavaScript从HTML中删除。)

All of the common JavaScript libraries, Prototype, ExtJS, Dojo, JQuery, YUI, etc. provide nice wrappers around events that occur as the document is loaded.

(所有常见的JavaScript库,Prototype,ExtJS,Dojo,JQuery,YUI等都为文档加载时发生的事件提供了很好的包装。)

You can listen for the window onLoad event, and react to that, but onLoad is not fired until all resources have been downloaded, so your event handler won't be executed until that last huge image has been fetched.

(您可以侦听窗口onLoad事件,并对此作出反应,但是在下载所有资源之前不会触发onLoad,因此在获取最后一个巨大的图像之前不会执行事件处理程序。)

In some cases that's exactly what you want, in others you might find that listening for when the DOM is ready is more appropriate - this event is similar to onLoad but fires without waiting for images, etc. to download.

(在某些情况下,这正是您想要的,在其他情况下,您可能会发现在DOM准备好时进行监听更合适 - 此事件类似于onLoad,但无需等待图像等即可下载。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...