最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript - Event listener for when all elements of class are loaded - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 3

You'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>

发布评论

评论列表(0)

  1. 暂无评论