Check if image exists on server using JavaScript?

前端 未结 12 935
抹茶落季
抹茶落季 2020-11-22 06:24

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

12条回答
  •  借酒劲吻你
    2020-11-22 07:27

    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.

提交回复
热议问题