Last active
April 17, 2025 16:11
-
-
Save kinngh/fe1863384d9a04e56e590dcd14e5f73d to your computer and use it in GitHub Desktop.
Load your JS despite "Speed Optimization Apps" monkey patching basic document events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Previous | |
document.addEventListener("DOMContentLoaded", async function () => {}); | |
//Patched | |
/** | |
* | |
* First, pull your callback into an independent function | |
* Here we call it `boot` since that's what I wanna shove up | |
* "optimization" apps' butts. | |
* | |
*/ | |
// Add this in <head> | |
const nativeAdd = EventTarget.prototype.addEventListener; | |
const nativeOnReadyState = Object.getOwnPropertyDescriptor(Document.prototype, 'readyState').get; | |
// 1) If DOM is already past loading, just run | |
if (document.readyState !== "loading") { | |
boot(); | |
// 2) Otherwise schedule via the *native* DOMContentLoaded | |
} else { | |
nativeAdd.call(document, "DOMContentLoaded", boot); | |
// 3) Window‑onload as a last DOM fallback | |
nativeAdd.call(window, "load", boot); | |
// 4) IE8‑style onreadystatechange | |
if ("attachEvent" in document) { | |
document.attachEvent("onreadystatechange", () => { | |
if (document.readyState === "complete") boot(); | |
}); | |
} | |
// 5) Polling fallback | |
(function poll() { | |
const state = document.readyState; // using the browser getter | |
if (state === "interactive" || state === "complete") { | |
boot(); | |
} else { | |
setTimeout(poll, 50); | |
} | |
})(); | |
} | |
// 6) reinit on section load | |
nativeAdd.call(document, "shopify:section:load", boot); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment