Skip to content

Commit

Permalink
Track DOM content loaded for ready() function (#1688)
Browse files Browse the repository at this point in the history
Track whether DOMContentLoaded has been fired
  • Loading branch information
alexpetros authored Aug 16, 2023
1 parent bfd7965 commit 93bd81b
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/htmx.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 93bd81b

Please sign in to comment.