Search code examples
javascriptevent-listenerpageload

Let window 'load' Event Listener be triggered before some specific images finish loading


So, I'm using the following code to show a loader in my Website:

$(window).on("load", function(){
    $(".loader").fadeOut("slow");
})

But there's a Carousel which has many images. I would like to "exclude" those images from the loading, so the event 'load' gets triggered before those images finish loading. Because then the loader would fade, but the images of the carousel which are almost at the end of the website would keep loading without preventing the user to see the website.

Is there a way to do that? (like adding a class to the images I want to exlude from the 'load' event listener or something...)


Solution

  • So, the only way I found to do this, is by adding an attribute (in this example: data-src) with the actual src to the images i don't want to wait to load:

    <img data-src="example.jpg" src="">
    

    Then you just need to load the images after the window Event 'load' is called:

    window.addEventListener('load', () => {
        const imgs = document.querySelectorAll('[data-src]');
        imgs.forEach(img => {
            img.setAttribute('src', img.getAttribute('data-src'));
        });
    });
    

    I believe this is a very primitive way of implementing a 'lazy loading', but it works for now...