$(function() {
$("<img>", {
src: "http://goo.gl/GWtGo",
error: function() { alert("error!"); },
load: function() { alert("ok"); }
});
});
Got inspiration from How can I test if a URL is a valid image (in javascript)?
UPDATE
The next step will be: how can I encapsulate this logic into a function. I tried this -> http://jsfiddle.net/wp7Ed/2/
$(function() {
function IsValidImageUrl(url) {
$("<img>", {
src: url,
error: function() { return false; },
load: function() { return true; }
});
}
alert(IsValidImageUrl("http://goo.gl/GWtGo"));
alert(IsValidImageUrl("http://error"));
});
but of course it fails... how can I return from an internl event handler? Or how can I implement this?
To check if a url is an image, call the test() method on a regular expression that matches an image extension at the end of a string, e.g. . png or . jpg . The test() method will check if the url ends with an image extension and will return true if it does.
On your computer, go to images.google.com. Search for the image. In Images results, click the image. At the top of your browser, click the address bar to select the entire URL.
var urlExists = function(url){ //When I call the function, code is still executing here. $. ajax({ type: 'HEAD', url: url, success: function() { return true; }, error: function() { return false; } }); //But not here... }
You cannot ever turn an asynchonous call into a synchronous one in javascript.
error
and load
are asynchronous events, so you have to do it like this:
function IsValidImageUrl(url) {
$("<img>", {
src: url,
error: function() { alert(url + ': ' + false); },
load: function() { alert(url + ': ' + true); }
});
}
IsValidImageUrl("http://goo.gl/GWtGo");
IsValidImageUrl("http://error");
or you can parse in callback function you define elsewhere like this:
function myCallback(url, answer) {
alert(url + ': ' + answer);
}
function IsValidImageUrl(url,callback) {
$("<img>", {
src: url,
error: function() { callback(url, false); },
load: function() { callback(url, true); }
});
}
IsValidImageUrl("http://goo.gl/GWtGo", myCallback);
IsValidImageUrl("http://error", myCallback);
The clean and performant version skips the jQuery overhead like this
function myCallback(url, answer) {
alert(url + ': ' + answer);
}
function IsValidImageUrl(url, callback) {
var img = new Image();
img.onerror = function() { callback(url, false); }
img.onload = function() { callback(url, true); }
img.src = url
}
IsValidImageUrl("http://goo.gl/GWtGo", myCallback);
IsValidImageUrl("http://error", myCallback);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With