本文介绍了onload操作和底部脚本中的操作有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用body onload有什么功能上的区别:

Is there any functional difference between using body onload:

<!DOCTYPE html>
<html>
<head>
    <title>testing body onload</title>
</head>
<body onload="fu('this is from body onload')">
    <h2 id="I1">nothing yet</h2>
    <script>
        function fu (msg) {
            document.getElementById("I1").innerHTML = msg ;
        }
    </script>
</body>
</html>

一方面

并在正文末尾执行脚本:

on the one hand and executing a script at the end of the body:

<!DOCTYPE html>
<html>
<head>
    <title>testing body onload</title>
</head>
<body>
    <h2 id="I1">nothing yet</h2>
    <script>
        function fu (msg){
            document.getElementById("I1").innerHTML = msg ;
        }
        fu('this is from bottom script') ;
    </script>
</body>
</html>

第二个对我来说似乎更好,当然是在加载页面时还有更多操作要做的时候.但是也许有一个我不知道的陷阱?

The second seems better to me, certainly when there are more actions to do when a page is loaded. But maybe there is a pitfall I don't know?

推荐答案

是的.将您的代码放在底部就像是将其放在domready事件中,而不是onload上.

Yes, there is. Putting your code at the bottom is like putting it in a domready event, not onload.

Domready表示已读取html代码(因此dom已准备就绪,换句话说,您现在可以使用js选择器找到dom元素),而onload则表示所有资产(img,css等).也被加载(因此,事件要长得多).

Domready means that the html code was read (so the dom is ready, or in other words, you can now find dom elements with js selectors), while onload means that all the assets (img, css, etc..) are loaded as well (so, a much longer event).

也请参考MDN文档:

(这基本上类似于jquery的domready,它是文档对象的事件): https://developer.mozilla.org/zh-CN/docs/Web/Events/DOMContentLoaded

(this is basically like jquery's domready, and it's a document object's event):https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

这是onload事件,它是窗口对象的事件: https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalEventHandlers/onload

this is the onload event, and it's a window object's event:https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

这篇关于onload操作和底部脚本中的操作有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 18:49