0

How can I stop images from being loaded by below's jQuery each() function?

As soon as a modal window opens, I load images as follow:

HTML:

<img data-src='image1.jpg'/>
<img data-src='image2.jpg'/>
<img data-src='image3.jpg'/>

jQuery:

$('img[data-src]').each(function(){
    var imgsrc = $(this).attr('data-src');
    $(this).attr('src',imgsrc).on('load',function(){
        $(this).removeAttr('data-src');
    });
});

This works great, but I would like to abort this when the modal is closed. What's the best way of doing this?

The problem is that upon selecting an image in the modal, a larger size is being loaded. But that image doesn't appear until all the images in the modal finish loading.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
bart
  • 14,958
  • 21
  • 75
  • 105
  • Check out this https://stackoverflow.com/questions/6707509/intercepting-image-load-request-of-the-browser. I do not believe you can really stop that. – wannadream Oct 25 '18 at 01:24
  • Doing a `return` will exit the `each` loop, e.g. `if (!modalVisible) return;` as the first line. – Tyler Roper Oct 25 '18 at 01:35
  • 1
    @TylerRoper But the images are already in pending status. – bart Oct 25 '18 at 01:42
  • The only way would be to reload or redirect, interrupting the image download. If your images are taking that long to load, you may want to invest some time in compressing the images more. – Heretic Monkey Oct 25 '18 at 04:00

1 Answers1

0

If I understand your problem correctly. So the solution may be like this:

var modal = $('.modal');

var onshown = function () {
    for (var img of Array.from(modal.find('img')).map(x => $(x))) {
        var source = img.data('src');
        // or
        // var source = img.attr('data-src');

        var image = new Image();

        image.onload = function () {
            // the image with the source is loaded successful
            img.attr('src', source);

            // or
            // img.prop('src', source);

            // remove the "data-src" attribute

            img.removeAttr('data-src');

            // or
            // img.attr('data-src', undefined);
        };

        image.src = source;
    }
};

modal.on('shown.bs.modal', onshown).modal();

By using for loop instead of $.fn.each, you can stop whenever you want using break or return keyword.

More information about the event shown.bs.modal.

Hope this helps!

Tân
  • 1
  • 15
  • 56
  • 102