Home > Mobile >  Javascript load Eventlistener
Javascript load Eventlistener

Time:12-26

I just wanted to ask how do you ensure that element details (e.g position in viewport, getBoundingClientRect) are correct when loading your page for the first time. Currently I have a problem with a normal div-element. It is displayed right after an image which i get with a fetch statement. I used the load-event on window and after the Page is loaded I get the information of the position of the div-element. Unfortunately the load-fires before the Image is loaded and that means the position details are wrong. How and when do you use the load Event? And what Else can i do to ensure i receive the right position details.

Html <div ></div> <div ></div>

Js window.addEventListener("load",()=>{console.log(document.querySelector(".position").getBoundingClientRect());}

Many thanks Regards Kat

CodePudding user response:

You'd need to call the getBoundingClientRect() after the image has loaded, which means when your fetch call has resolved (as it is executed asynchronously).

To keep in mind: The load event does not include asnyc fetched resources (as those are handled dynamically). For more info on the load event see the documentation.

CodePudding user response:

'load' event listener can also be applied on images like this:

var img = new Image();
img.src = "img.jpg";
img.onload = function () {
   alert("image is loaded");
}

Also you can get getBoundingClientRect() properties after the fetch:

fetch('image.png').then(i => {
  //get size
})

  • Related