aboutsummaryrefslogtreecommitdiff
path: root/webAO/utils/fileExists.ts
blob: 748bc1fed18ed3dbe5d1f92cd82ae04b85765ab1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const cache = new Map<string, Promise<boolean>>();

export default function fileExists(url: string): Promise<boolean> {
  const cached = cache.get(url);
  if (cached !== undefined) return cached;

  const promise = new Promise<boolean>((resolve) => {
    const xhr = new XMLHttpRequest();
    xhr.open("HEAD", url);
    xhr.onload = function checkLoad() {
      if (xhr.readyState === 4) {
        resolve(xhr.status === 200);
      }
    };
    xhr.onerror = function checkError() {
      resolve(false);
    };
    xhr.send(null);
  });

  cache.set(url, promise);
  return promise;
}