jQuery/JavaScript to replace broken images

后端 未结 30 2548
我寻月下人不归
我寻月下人不归 2020-11-21 05:50

I have a web page that includes a bunch of images. Sometimes the image isn\'t available, so a broken image is displayed in the client\'s browser.

How do I use jQuery

30条回答
  •  逝去的感伤
    2020-11-21 06:04

    I couldn't find a script to suit my needs, so I made a recursive function to check for broken images and attempt to reload them every four seconds until they are fixed.

    I limited it to 10 attempts as if it's not loaded by then the image might not be present on server and the function would enter an infinite loop. I am still testing though. Feel free to tweak it :)

    var retries = 0;
    $.imgReload = function() {
        var loaded = 1;
    
        $("img").each(function() {
            if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
    
                var src = $(this).attr("src");
                var date = new Date();
                $(this).attr("src", src + "?v=" + date.getTime()); //slightly change url to prevent loading from cache
                loaded =0;
            }
        });
    
        retries +=1;
        if (retries < 10) { // If after 10 retries error images are not fixed maybe because they
                            // are not present on server, the recursion will break the loop
            if (loaded == 0) {
                setTimeout('$.imgReload()',4000); // I think 4 seconds is enough to load a small image (<50k) from a slow server
            }
            // All images have been loaded
            else {
                // alert("images loaded");
            }
        }
        // If error images cannot be loaded  after 10 retries
        else {
            // alert("recursion exceeded");
        }
    }
    
    jQuery(document).ready(function() {
        setTimeout('$.imgReload()',5000);
    });
    

提交回复
热议问题