- 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
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
import * as event from "./event.js";
import { nodeJS } from "./platform.js";
// track if DOMContentLoaded was called already
let readyBound = false;
// is the DOM ready ?
let isDOMReady = false;
// check if the dom is ready
function _domReady() {
// Make sure that the DOM is not already loaded
if (!isDOMReady) {
// be sure document.body is there
if (typeof globalThis.document !== "undefined" && !globalThis.document.body) {
return setTimeout(_domReady, 13);
}
// clean up loading event
if (typeof globalThis.document !== "undefined" && typeof globalThis.document.removeEventListener === "function") {
globalThis.document.removeEventListener(
"DOMContentLoaded",
_domReady,
false
);
}
if (typeof globalThis.removeEventListener === "function") {
// remove the event on globalThis.onload (always added in `onReady`)
globalThis.removeEventListener("load", _domReady, false);
}
// execute all callbacks
event.emit(event.DOM_READY);
// Remember that the DOM is ready
isDOMReady = true;
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event
export function DOMContentLoaded(fn) {
// If the DOM is already ready
if (isDOMReady) {
// Execute the function immediately
fn.call(globalThis, []);
}
else {
// else add the function to the DOM_READY event
event.once(event.DOM_READY, fn, globalThis);
// bind dom load event if not done yet
if (!readyBound) {
// directly call domReady if document is already "ready"
if (nodeJS === true || (typeof globalThis.document !== "undefined" && globalThis.document.readyState === "complete")) {
// defer the fn call to ensure our script is fully loaded
globalThis.setTimeout(_domReady, 0);
}
else {
if (typeof globalThis.document !== "undefined" && typeof globalThis.document.addEventListener === "function") {
// Use the handy event callback
globalThis.document.addEventListener("DOMContentLoaded", _domReady, false);
}
// A fallback to globalThis.onload, that will always work
globalThis.addEventListener("load", _domReady, false);
}
readyBound = true;
}
}
}