问题
I am currently using following script in a hover-functionality:
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
It loads every image each after the other, causing to slow down the entire website (or even crashing).
Is there a way to check if an image exists, though prevent loading it (fully) using javascript?
Thanks alot!
回答1:
Since JavaScript (and therefore jQuery) is client-side and the image resides server-side before loading there is no way to check to see if the image exists without using Ajax or your server-side scripting to make sure the image exists.
回答2:
There's no way determining using javascript or jQuery if an image exists without loading it.
workaround:
The only way to check if an image exists on the server side would be to try loading the image to a hidden div or something and check if the image is there or not and then display it.
or you can use some server side language of your choice like ( php, asp, jsp, python, etc ) and send the request to the image to the server side language (preferably using AJAX) and let the server side script check if the image exists or not and send back the image if present or sent an error code if not present.
回答3:
My solution:
function imageExists(url) {
return new Promise((resolve, reject) => {
const img = new Image(url);
img.onerror = reject;
img.onload = resolve;
const timer = setInterval(() => {
if (img.naturalWidth && img.naturalHeight) {
img.src = ''; /* stop loading */
clearInterval(timer);
resolve();
}
}, 10);
img.src = url;
});
}
Example:
imageExists(url)
.then(() => console.log("Image exists."))
.catch(() => console.log("Image not exists."));
回答4:
Here's how you can check if an image exists:
function checkImage(src) {
var img = new Image();
img.onload = function() {
// code to set the src on success
};
img.onerror = function() {
// doesn't exist or error loading
};
img.src = src; // fires off loading of image
}
Here's a working implementation http://jsfiddle.net/jeeah/
来源:https://stackoverflow.com/questions/13937116/check-if-image-exists-without-loading-it