Skip to content
Open
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 20 additions & 14 deletions src/htmx.js
Original file line number Diff line number Diff line change
Expand Up @@ -5056,25 +5056,31 @@ var htmx = (function() {
//= ===================================================================
// Initialization
//= ===================================================================
var isReady = false
getDocument().addEventListener('DOMContentLoaded', function() {
isReady = true
})

/**
* Execute a function now if DOMContentLoaded has fired, otherwise listen for it.
* Execute a function once the DOM has loaded.
*
* If the DOM is still loading, the function will be run as a listener for
* the DOMContentLoaded event. Otherwise, the function will be synchronously
* executed now.
*
* This is tricky to get right since the DOMContentLoaded event only fires
* ones. We need to ensure we always wait for it if the DOM is still loading,
* but that we never wait for it if it's already been fired.
*
* This function uses isReady because there is no reliable way to ask the browser whether
* the DOMContentLoaded event has already been fired; there's a gap between DOMContentLoaded
* firing and readystate=complete.
* This is extra tricky if HTMX was loaded using a script tag with the async
* attribute (and no defer attribute). In that case the script will execute as
* soon as it has been loaded from the network, regardless of the value
* of readyState or whether DOMContentLoaded has been fired or not. In
* paricular, there is a gap of time where DOMContentLoaded has been fired,
* but readyState is not "complete".
*/
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 {
if (getDocument().readyState === 'loading') {
// Loading hasn't finished yet
getDocument().addEventListener('DOMContentLoaded', fn)
} else {
// `DOMContentLoaded` has already fired
fn()
}
}

Expand Down