admin管理员组文章数量:1424415
Is there a way in Javascript to execute code once every element of type/class/tag etc. has been loaded?
Something like:
document.getElementsByClassName("test").addEventListener("onload", ()=> { executeStuffHere(); });
If not, is there a similar way to do this for images? (Execute code once all images have been loaded)
Is there a way in Javascript to execute code once every element of type/class/tag etc. has been loaded?
Something like:
document.getElementsByClassName("test").addEventListener("onload", ()=> { executeStuffHere(); });
If not, is there a similar way to do this for images? (Execute code once all images have been loaded)
Share Improve this question asked Mar 13, 2021 at 4:08 notsoscottishscotnotsoscottishscot 3681 gold badge4 silver badges11 bronze badges 3-
Use
.addEventListener("load"
– quicVO Commented Mar 13, 2021 at 4:10 -
1
and
DOMContentLoaded
– quicVO Commented Mar 13, 2021 at 4:10 - This should help stackoverflow./questions/799981/… – a.mola Commented Mar 13, 2021 at 4:14
2 Answers
Reset to default 3You'll need a loop. You could make a count of the number of images, then decrement each time an image loads. Inside the callback, call the final function once the count gets to 0.
const images = document.getElementsByClassName("test");
let imagesLeft = images.length;
for (const image of images) {
image.addEventListener('load', () => {
imagesLeft--;
if (imagesLeft === 0) executeStuffHere();
});
}
Note that .addEventListener("onload"
will not work. You must use load
.
You could also add error listeners if you want executeStuffHere
to run once everything is finished, even if some errored.
If some images might already be loaded, check if they're .plete
first before adding the listener (and if they are, decrement).
First you wait for DOMContentLoaded or ensure that document.readyState is interactive
or loaded
, then select all nodes maching the criteria you want, loop over them, and execute the code. The method document.querySelectorAll()
returns a NodeList, which you can coerce into an array
The main thing to note here is you're not waiting for each node to load. You're waiting for the whole document to load and then iterating through the DOM tree.
const fireOnAllYeses = () => {
Array.from(document.querySelectorAll('.yes')).forEach(domNode => {
// execute code here
console.log( domNode.innerText );
});
};
document.addEventListener('DOMContentLoaded', fireOnAllYeses);
<main>
<div class="yes">I am yes 1</div>
<div class="no">I am no 1</div>
<div class="yes">I am yes 2</div>
<div>I am some div</div>
</main>
本文标签: htmlJavascriptEvent listener for when all elements of class are loadedStack Overflow
版权声明:本文标题:html - Javascript - Event listener for when all elements of class are loaded - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745425493a2658091.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论