diff options
author | Carson Gross <carson@bigsky.software> | 2023-11-20 16:17:21 -0700 |
---|---|---|
committer | Carson Gross <carson@bigsky.software> | 2023-11-20 16:17:21 -0700 |
commit | d5203c3b423fcac5928cb5fbc6053f62162e037e (patch) | |
tree | 6ea42c12d380df9b8596862dcec858f10866458d | |
parent | 52d19a47fb2723debb2bb01546c864c6ef3acde6 (diff) | |
parent | 78a9ecf17079fcdfa3d674700d8338b60f14a058 (diff) | |
download | htmx-d5203c3b423fcac5928cb5fbc6053f62162e037e.tar.gz htmx-d5203c3b423fcac5928cb5fbc6053f62162e037e.zip |
Merge remote-tracking branch 'origin/dev' into dev
-rw-r--r-- | src/htmx.js | 43 |
1 files changed, 26 insertions, 17 deletions
diff --git a/src/htmx.js b/src/htmx.js index 82499875..1f0709d7 100644 --- a/src/htmx.js +++ b/src/htmx.js @@ -3752,25 +3752,34 @@ 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. + * We want to initialize the page elements after DOMContentLoaded + * fires, but there isn't always a good way to tell whether + * it has already fired when we get here or not. */ - function ready(fn) { - // 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); + function ready(functionToCall) { + // call the function exactly once no matter how many times this is called + var callReadyFunction = function() { + if (!functionToCall) return; + functionToCall(); + functionToCall = null; + }; + + if (getDocument().readyState === "complete") { + // DOMContentLoaded definitely fired, we can initialize the page + callReadyFunction(); + } + else { + /* DOMContentLoaded *maybe* already fired, wait for + * the next DOMContentLoaded or readystatechange event + */ + getDocument().addEventListener("DOMContentLoaded", function() { + callReadyFunction(); + }); + getDocument().addEventListener("readystatechange", function() { + if (getDocument().readyState !== "complete") return; + callReadyFunction(); + }); } } |