about summary refs log tree commit diff
path: root/app/javascript/flavours/glitch/ready.js
diff options
context:
space:
mode:
Diffstat (limited to 'app/javascript/flavours/glitch/ready.js')
-rw-r--r--app/javascript/flavours/glitch/ready.js32
1 files changed, 32 insertions, 0 deletions
diff --git a/app/javascript/flavours/glitch/ready.js b/app/javascript/flavours/glitch/ready.js
new file mode 100644
index 000000000..e769cc756
--- /dev/null
+++ b/app/javascript/flavours/glitch/ready.js
@@ -0,0 +1,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);
+    }
+  });
+}