0

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...)

Soulss
  • 171
  • 1
  • 12
  • you want to exclude those carousel images from load event? – John Dec 06 '21 at 20:53
  • @John exactly, so the page loads everything, but the images from the carousel that take too long to load doesn't interfere with the rest. – Soulss Dec 06 '21 at 20:55
  • do you have access to change the carousel images `src` attribute? or does the library have lazyload feature? because when lazyloading, the images wont have `src` attribute and can not load without any trigger (browser wont load them automaticly) – John Dec 06 '21 at 21:00
  • @John I have access to the src attribute, I'm using SplideJS carousel btw. I believe i'll have to mannually check for the images i need to be loaded using javascript and then deactivate the 'loader' div i'm using... – Soulss Dec 06 '21 at 21:09
  • Might I suggest browser native lazy loading? https://web.dev/browser-level-image-lazy-loading/. It wont work for everyone, but it does a pretty good job of downloading the right amount of images based on your bandwidth and device size. – Matt Korostoff Dec 07 '21 at 00:21
  • @MattKorostoff Yeah, i just basically implemented a lazy loading with JS. I thinks is the only way to achieve this. – Soulss Dec 07 '21 at 00:58

1 Answers1

3

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...

Soulss
  • 171
  • 1
  • 12