How to determine when all images are loaded and items are displayed at their respective heights

How can I verify (using jquery or vanilla js ) that all the images on the page are loaded and that they were displayed at their final, full height, and that their parent elements are set to this height?

I implement a function scrollspyusing jquery - that determines where the user is on the page and selects his position on nav, updating his position as it scrolls. For this to work correctly, I need to know the offset.top of each section on the page on which I want to follow. If I calculate offset.top too soon before all the images are loaded and displayed at their full height, the calculation of offset (). Top will be incorrect. I want to avoid bias (). Top calculation too many times.

Things I tried that do not fit my needs:

$(document).ready() and $(window).onload() are too early, since the images may not have been displayed at their full height, so they will not be displayed at their full height.

imagesLoaded library. the same problem, as mentioned above, does not allow for rendering images to full height.

+4
source share
2 answers

Based on my experience, I think this is not trivial. window.onloadmay help, but it is not reliable if images are loaded dynamically. I used to use some kind of hack to make it workable. Basically, I used window.setIntervaland checked if the image was really accessible by looking at the property naturalWidth(see https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement ).

Here is an example implementation: https://jsfiddle.net/yu8zr20h/

0

. Y Y- , , , nav.

, html-:

<div id="firstContainer">
    <!-- Some content -->
</div>

<div id="secondContainer">
    <!-- Some other content -->
</div>

html, document.gelElementBtId('element-id').offsetTop

, scrollY

JSFiddle.

0

Source: https://habr.com/ru/post/1667774/


All Articles