Trigger Event after All Images Loaded

visibility 25 comment 0 access_time 29 days ago languageEnglish

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 Promise to call the function once after all images are loaded.

Example code


        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();
        // });
        // });
            Array.from($images).filter(img => !img.comleted)
                .map(img => new Promise(resolve => { 
                    img.addEventListener('load', resolve); 
                    img.addEventListener('error', resolve);
            () => {
                console.log('images finished loading');

The output looks like the following screenshot:

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

Credits to



copyright This page is subject to Site terms.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

More from Kontext
visibility 232
thumb_up 0
access_time 10 months ago
Bootstrap 5 Masonry Cards Layout
visibility 238
thumb_up 1
access_time 29 days ago