I'm trying to check if an image exists given a url using javascript, but my code is not working. Thanks!
Here's my function :
function verifyImageURL(url, callBack) {
var img = new Image();
img.src = url;
img.onload = function () {
callBack(true);
};
img.onerror = function () {
callBack(false);
};
}
And Here's how I call it:
var url = "http://greenstyle.com.br/wp-content/uploads/2012/09/Tucano-imagem-Silvia-Kochen-Wordpress.jpg";
verifyImageURL(url, function (imageExists) {
if (imageExists === true) {
alert("Image Exists");
} else {
alert("Image does not Exist");
}
});
This question hasn't had activity in a long time, but since I saw another recent answer, I thought I would share a solution which fits the asker's example pattern of using a callback, but alternatively returns a promise if no callback argument is provided:
See code in the TypeScript Playground to view types and the overloaded function signature
function loadImage (url, timeoutOrCallback, maybeCallback) { let timeout; let callback; if (typeof timeoutOrCallback === 'number') { timeout = timeoutOrCallback; if (typeof maybeCallback === 'function') callback = maybeCallback; } else if (typeof timeoutOrCallback === 'function') callback = timeoutOrCallback; const promise = callback ? undefined : new Promise(resolve => void (callback = resolve)); const onlyRunOnce = {once: true}; let timerId = 0; let done = false; if (typeof timeout === 'number') { timerId = setTimeout(() => { done = true; callback(false); }, timeout); } const img = new Image(); img.addEventListener('load', () => { if (done) return; clearTimeout(timerId); done = true; callback(true); }, onlyRunOnce); img.addEventListener('error', () => { if (done) return; clearTimeout(timerId); done = true; callback(false); }, onlyRunOnce); img.src = url; return promise; } // Usage examples: function asyncExample (url, logId) { const timeout = 3e3; // 3s loadImage(url, timeout).then(imageLoaded => { console.log(`${logId}: async with timeout:`, imageLoaded) }); loadImage(url).then(imageLoaded => { console.log(`${logId}: async:`, imageLoaded) }); } function callbackExample (url, logId) { const timeout = 3e3; // 3s let cb = imageLoaded => console.log(`${logId}: callback with timeout:`, imageLoaded); loadImage(url, timeout, cb); cb = imageLoaded => console.log(`${logId}: callback:`, imageLoaded); loadImage(url, cb); } let url = 'https://i.stack.imgur.com/TxzmG.jpg'; asyncExample(url, 'SO image'); callbackExample(url, 'SO image'); url = 'https://invalid.example/image.jpg'; asyncExample(url, 'invalid image'); callbackExample(url, 'invalid image');
试试这个方法
var x = new XMLHttpRequest(); x.open("get", url, true);x.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) {alert('exist');}else{alert('does not exist'};}; x.send();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.