简体   繁体   中英

Javascript load Eventlistener

I just wanted to ask how do you ensure that element details (eg 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 class="wrapperImg"></div> <div class="position"></div>

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

Many thanks Regards Kat

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 .

'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 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM