Trigger Event after All Images Loaded

Raymond Tang Raymond Tang 0 1568 1.14 index 9/18/2021

When implementing Bootstrap 5 Masonry Cards Layout, I added a event handler after each image is loaded to layout the cards using Masonry JavaScript library. The drawback of that approach is that the function will be called as many times as the images count. In a modern environment, we could just use Promiseto call the function once after all images are loaded.

Example code

<script>
        var $grid = document.querySelector('.row');        var msnry = new Masonry($grid, {            itemSelector: '.col',            percentPosition: true        });        var $images = $grid.querySelectorAll('.card img');        // $images.forEach(function (el) {        //     el.addEventListener('load', function () {        //         console.log("Image is loaded: " + el.getAttribute("src"));        //         msnry.layout();        //     });        // });
        Promise.all(            Array.from($images).filter(img => !img.complete)                .map(img => new Promise(resolve => {                     img.addEventListener('load', resolve);                     img.addEventListener('error', resolve);                })                )        ).then(            () => {                console.log('images finished loading');                msnry.layout();            }        );    </script> 

The output looks like the following screenshot:

2021091801630-image.png

warning Promise is not supported by all browsers but is supported by majority of modern browsers. 

Credits to https://stackoverflow.com/questions/11071314/javascript-execute-after-all-images-have-loaded.

References

Promise

javascript

Join the Discussion

View or add your thoughts below

Comments