From cf9337c90a41518a0632b473805bfe76d7fdffb3 Mon Sep 17 00:00:00 2001 From: Alexander Petros Date: Wed, 9 Aug 2023 14:03:18 -0400 Subject: [PATCH] Track whether DOMContentLoaded has been fired --- src/htmx.js | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/htmx.js b/src/htmx.js index 54b0e9d6b..26cc929e6 100644 --- a/src/htmx.js +++ b/src/htmx.js @@ -3603,9 +3603,22 @@ return (function () { //==================================================================== // Initialization //==================================================================== + var isReady = false + getDocument().addEventListener('DOMContentLoaded', function() { + isReady = true + }) + /** + * Execute a function now if DOMContentLoaded has fired, otherwise listen for it. + * + * This function uses isReady because there is no realiable way to ask the browswer whether + * the DOMContentLoaded event has already been fired; there's a gap between DOMContentLoaded + * firing and readystate=complete. + */ function ready(fn) { - if (getDocument().readyState === 'complete') { + // Checking readyState here is a failsafe in case the htmx script tag entered the DOM by + // some means other than the initial page load. + if (isReady || getDocument().readyState === 'complete') { fn(); } else { getDocument().addEventListener('DOMContentLoaded', fn);