wait until images in background (css) are loaded

后端 未结 5 1156
自闭症患者
自闭症患者 2021-01-02 07:29

Let\'s say we have a slideshow of pictures. the thumbnails of those pictures are showed in div wrapper with a slider (that I created with Jquery) and each image is included

5条回答
  •  南笙
    南笙 (楼主)
    2021-01-02 07:57

    It looks for elements with src attribute or backgroundImage css property and calls an action function when theirs images loaded.

    /**
     * Load and wait for loading images.
     */
    function loadImages(images, action){
        var loaded_images = 0;
        var bad_tags = 0;        
    
        $(images).each(function() {
        //alert($(this).get(0).tagName+" "+$(this).attr("id")+" "+$(this).css("display"));
            var image = new Image();
            var src = $(this).attr("src");
            var backgroundImage = $(this).css("backgroundImage");            
            // Search for css background style
            if(src == undefined && backgroundImage != "none"){
                var pattern = /url\("{0,1}([^"]*)"{0,1}\)/;                
                src = pattern.exec(backgroundImage)[1];                
            }else{
                bad_tags++;
            }
            // Load images
            $(image).load(function() {
                loaded_images++;                
                if(loaded_images == ($(images).length - bad_tags))
                    action();
            })
            .attr("src", src);
        });
    }
    

提交回复
热议问题