Search code examples
javascripthtml5-canvasonload

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


After reading another post, I am still confused about onload. Setting body onload without using the <body> tag

After successfully testing the animation from Adobe Animate 2021 in three browsers (edge, firefox, and chrome), I planned on adding it to my Dreamweaver 2021 project. I noted that the tags inside the "adobe-animation.html" have the animation canvas right below the first body tag.

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

After changing the tags and adding it to my project, the animation didn't play.

I went back to "adobe-animation.html" and only changed the body tag to a div and nesting it inside a new body.

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

It didn't work, like I expected.

After testing it further. I noticed that onload="init() needs to be inside the body tag. What is onload="init()? Why does it need to be inside the first body tag?


Solution

  • Use addEventListener

    Not enough information as to why its not called however it is bad practice to assign events directly as they can easily be overwritten by you or some 3rd party script and as such can NOT guarantee the listener will be called.

    You should never use

    <sometag onsomeevent = "doSomething()"/>
    

    Always assign event listeners using EventTarget.addEventListener

    The best eventTarget to use in this case would be the window AKA globalThis.

    Thus you would call init using

    <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>