javascript - Turn an image's onError function into a return - Stack Overflow

So I need a function to test if an image can load or not. Here's what I've got:function imgEx

So I need a function to test if an image can load or not. Here's what I've got:

function imgExists(url){
    var img = new Image();
    img.onerror = function(){
        alert('error')
    }
    img.onload = function (){
    alert('load')
    }
    img.src = url;
}

imgExists('/[email protected]')

The issue is that the alerts are trapped in their won functions. How can I get the imgExists() function to return true if the image loads and false if it does not?

So I need a function to test if an image can load or not. Here's what I've got:

function imgExists(url){
    var img = new Image();
    img.onerror = function(){
        alert('error')
    }
    img.onload = function (){
    alert('load')
    }
    img.src = url;
}

imgExists('http://hashtraffic./img/[email protected]')

The issue is that the alerts are trapped in their won functions. How can I get the imgExists() function to return true if the image loads and false if it does not?

Share Improve this question asked Jun 21, 2012 at 12:30 altalt 14k21 gold badges82 silver badges124 bronze badges 3
  • 6 The image will load asynchronously, so you cannot return a value immediately from the function. You will have to follow the deferred execution pattern and either provide a callback for your function to call, or have it return a Deferred object. – Frédéric Hamidi Commented Jun 21, 2012 at 12:32
  • Any examples? How do I provide a callback? – alt Commented Jun 21, 2012 at 12:34
  • You pass it as parameter to your function and call it inside the function when you have the result. – Felix Kling Commented Jun 21, 2012 at 12:35
Add a ment  | 

1 Answer 1

Reset to default 6

You need to use a callback, since your function is inherently asynchronous:

function imgExists(url, callback) {
    var img = new Image();
    img.onerror = function() {
        callback(false);
    }
    img.onload = function () {
        callback(true);
    }
    img.src = url;
}

function checkImage(exists) {
    alert("Image exists: " + exists); // Usage example.
}

imgExists('http://hashtraffic./img/[email protected]', checkImage);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745564172a4633293.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信