0

I want to apply preloading to image so i add class image-preload to and remove it after loading image finished. almost worked but some image doesn't remove image-preload after loading.

my Javascript bellow:

 <script >
        $(document).ready(function(){
            jQuery.preloadImages = function() {
                var set = $('.container img');
                if(set.length == 0) return;
                set.addClass('img-preload');
                var current = 0;
                var iterate = function() {
                    var obj = set[current];
                    jQuery(obj).on('load', function() {
                       $(this).removeClass('img-preload');
                    });
                    if(++current < set.length) iterate();
                };
                iterate();
            };

            jQuery.preloadImages();
        }());
    </script>

Edit:

My above example can remove image-preload class when i press ctr + f5 but not if i press only f5. I think it's related to my browser cache but i don't know how to resolve it?

  • What is the aim of adding this class? Can you please click edit, then `[<>]` snippet editor and provide a [mcve] - you can get images from lorempixel or placeholder.com – mplungjan May 13 '20 at 10:21
  • Also you do not actually preload the images in your code. You cannot add the load event handler to an image that has already loaded - which they have in the document.ready – mplungjan May 13 '20 at 10:22
  • What does $(this) refer to in this context? what is 'this'? – Yftach May 13 '20 at 10:29
  • @Yftach: It refers correctly to jQuery(obj) – Poul Bak May 13 '20 at 10:40

0 Answers0