我如何测试如果一个URL是一个有效的图像与超时的图像请求与javascript

How can I test if a URL is a valid image with timeout on image request with javascript?

本文关键字:一个 图像 何测试 超时 请求 javascript 有效 测试 URL 如果      更新时间:2023-09-26

我有这个javascript代码:

$(function() {
    $("<img>", {
        src: "http://urlpath/img.png",
        error: function() { alert("error!"); },
        load: function() { alert("ok"); }
    });
});

它的代码工作,但我需要为这个请求设置一个超时,以避免有一个缓慢的请求。

任何建议对我都很有用!

谢谢:D

也许你需要:

$.ajax({
    url: "test.html",
    error: function(){
        // will fire when timeout is reached
    },
    success: function(){
        //do something
    },
    timeout: 3000 // sets timeout to 3 seconds
});

[阅读]http://api.jquery.com/jQuery.ajax/

$(function() {
    timedout = false;
    var i = $("<img>", {
        src: "http://urlpath/img.png",
        error: function() { if (!timedout) { timedout = true; alert("error!"); } },
        load: function() { timedout = true; alert("ok"); }
    });
    window.setTimeout(function () { i.trigger('error'); i.remove(); }, 2000);
});

试试这个:

$(function() {
    var timed = false;
    var imgTO = setTimeout(function () {
        timed = true;
        alert("timed out");
    }, 2000);  // 2 second timeout
    $("<img>").on({
        error: function() {
            clearTimeout(imgTO);
            if (!timed) alert("error!");
        },
        load: function() {
            clearTimeout(imgTO);
            if (!timed) alert("ok");
        }
    }).attr("src", "http://urlpath/img.png");
});