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?
- 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
1 Answer
Reset to default 6You 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条)