Don't load hidden images

前端 未结 7 1148
旧时难觅i
旧时难觅i 2020-12-02 13:19

I have a bunch of hidden images on my website. Their container DIVs have style=\"display: none\". Depending on the user\'s actions, some images may be revealed via javascrip

7条回答
  •  一整个雨季
    2020-12-02 14:12

    The browser will load any images that has a src attribute set, so what you want to do is to use data-src in the markup and use JavaScript to set the src attribute when you want it to load.

    
    

    I created this tiny plugin that will take care of the problem:

    (function($){
        // Bind the function to global jQuery object.
        $.fn.reveal = function(){
            // Arguments is a variable which is available within all functions
            // and returns an object which holds the arguments passed.
            // It is not really an array, so by calling Array.prototype
            // he is actually casting it into an array.
            var args = Array.prototype.slice.call(arguments);
    
            // For each elements that matches the selector:
            return this.each(function(){
                // this is the dom element, so encapsulate the element with jQuery.
                var img = $(this),
                    src = img.data("src");
    
                // If there is a data-src attribute, set the attribute
                // src to make load the image and bind an onload event.
                src && img.attr("src", src).load(function(){
                    // Call the first argument passed (like fadeIn, slideIn, default is 'show').
                    // This piece is like doing img.fadeIn(1000) but in a more dynamic way.
                    img[args[0]||"show"].apply(img, args.splice(1));
                });
            });
        }
    }(jQuery));
    

    Execute .reveal on the image(s) you want to load/show:

    $("img.hidden").reveal("fadeIn", 1000);
    

    See test case on jsFiddle.

提交回复
热议问题