body.onload()事件将在 DOM 和所有相关资源(如图像)加载后调用。基本上, onload() 当页面完全加载了整个图像、iframe 和样式表等时将被调用。
例如,如果我们的页面包含更大尺寸的图像,那么onload()事件将等待图像完全加载。
例子:
HTML
GeeksForGeeks
HTML
GeeksForGeeks
输出:
这 document.ready()函数将在 DOM 加载后立即执行。它不会等待图像、脚本、对象、iframe 等资源被加载。
我们的代码中可以有多个document.ready()函数,但只允许一个body.onload() 。
例子:
HTML
GeeksForGeeks
输出:
body.onload 和 document.ready 的区别:
body.onload() | document.ready() |
---|---|
onload() will be called only when everything gets loaded. | This function is called as soon as DOM is loaded. |
It will wait till all resources like images, iframes, objects, scripts get loaded. | It will be called once DOM is loaded. |
We can have only one body.onload() function. | We can have multiple documents.ready() function in our page. |