about summary refs log tree commit diff
path: root/app/javascript/flavours/glitch/ready.js
blob: e769cc756079f0c1226b8055db8964e64344959c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// @ts-check

/**
 * @param {(() => void) | (() => Promise<void>)} callback
 * @returns {Promise<void>}
 */
export default function ready(callback) {
  return new Promise((resolve, reject) => {
    function loaded() {
      let result;
      try {
        result = callback();
      } catch (err) {
        reject(err);

        return;
      }

      if (typeof result?.then === 'function') {
        result.then(resolve).catch(reject);
      } else {
        resolve();
      }
    }

    if (['interactive', 'complete'].includes(document.readyState)) {
      loaded();
    } else {
      document.addEventListener('DOMContentLoaded', loaded);
    }
  });
}