HTML5 JavaScript 除非 onload="init() 在 body 标签内,否则动画不会播放。为什么?

HTML5 JavaScript Animation doesn't play unless onload="init() is inside the body tag. Why?

看了一篇post,我对onload还是一头雾水。 Setting body onload without using the <body> tag

在三种浏览器(edge、firefox 和 chrome)中成功测试 Adob​​e Animate 2021 的动画后,我计划将其添加到我的 Dreamweaver 2021 项目中。我注意到“adobe-animation.html”中的标签在第一个 body 标签正下方有动画 canvas。

<head>
<script>
....
</script>
</head>
<body onload="init();" style="margin:0px;"> //start of animation tags
.....
</body>

更改标签并将其添加到我的项目后,动画没有播放。

我回到“adobe-animation.html”,只将正文标签更改为 div 并将其嵌套在新正文中。

<body>
<div onload="init();" style="margin:0px;">      //originally <body>
....
</div>                                         //originally </body>
</body>

它没有像我预期的那样工作。

进一步测试后。我注意到 onload="init() 需要在 body 标签内。什么是 onload="init()?为什么它需要在第一个正文标签内?

使用addEventListener

关于为什么不调用它的信息不足,但是直接分配事件是不好的做法,因为它们很容易被您或某些第 3 方脚本覆盖,因此不能保证会调用侦听器。

你永远不应该使用

<sometag onsomeevent = "doSomething()"/>

始终使用 EventTarget.addEventListener

分配事件侦听器

最好的eventTarget to use in this case would be the window AKA globalThis.

因此您可以使用

调用init
<script>

// guarantee init is called
addEventListener("load", init(), {once: true}); // same as window.addEventListener but window
                                                // is the default object an thus not required

function init() { /*code*/ } 

</script>