How to cancel a jquery.load()?

前端 未结 7 1036
清酒与你
清酒与你 2020-11-29 07:30

I\'d like to cancel a .load() operation, when the load() does not return in 5 seconds. If it\'s so I show an error message like \'sorry, no picture loaded\'.

What I

7条回答
  •  醉酒成梦
    2020-11-29 08:01

    You could simply set a timeout before loading the image as well as testing for a load error.

    function LoadImage(yourImage) {
    
        var imageTimer = setTimeout(function () {
            //image could not be loaded:
            alert('image load timed out');
        }, 10000); //10 seconds
    
        $(yourImage).load(function (response, status, xhr) {
            if (imageTimer) {
    
                if (status == 'error') {
                    //image could not be loaded:
                    alert('failed to load image');
    
                } else {
                    //image was loaded:
                    clearTimeout(imageTimer);
                    //display your image...
                }
    
            }
        });
    
    }
    

提交回复
热议问题