onload event triggered even the node is removed from dom

53 Views Asked by At
<img id="img" src="src/abc.jpg" onload="imgload()"/>
<script>
   var img = document.getElementById("img");
   img.remove()
   function imgload(){
      console.log("image loaded now")
   }
</script>

Event though we removed the image from dom. the eventlistener was triggered. I know its a expected behaviour, but it seems like bug. please clarify.

1

There are 1 best solutions below

1
Alexander E On

This might not be an correct explanation for your question, but i try to expain it from my POV.

While performing some searches, it came to know that onload function on image is an asynchronous function as it is related to fetch request.

you can also refer this link

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>

<body>
  <div>
    <img src="https://images.pexels.com/photos/460672/pexels-photo-460672.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" id="img" alt="" srcset="" onload="imgload()" />
  </div>
  <script>
    var img = document.getElementById("img");
    img.remove();
    console.log('image removed');

    function imgload() {
      console.log(document);
      // run in the local system to see the document
    }
  </script>
</body>

</html>

while you run this code you will get output as Output image

you will know that the img is being removed from the DOM. Thus this is asynchronous and does not depend on the image tag it depends on the image request.