Using javascript is there a way to tell if a resource is available on the server? For instance I have images 1.jpg - 5.jpg loaded into the html page. I\'d like to call a Jav
Basicaly a promisified version of @espascarello and @adeneo answers, with a fallback parameter:
const getImageOrFallback = (path, fallback) => {
return new Promise(resolve => {
const img = new Image();
img.src = path;
img.onload = () => resolve(path);
img.onerror = () => resolve(fallback);
});
};
// Usage:
const link = getImageOrFallback(
'https://www.fillmurray.com/640/360',
'https://via.placeholder.com/150'
).then(result => console.log(result) || result)
// It can be also implemented using the async / await API.
Note: I may personally like the fetch solution more, but it has a drawback – if your server is configured in a specific way, it can return 200 / 304, even if your file doesn't exist. This, on the other hand, will do the job.