-
-
Notifications
You must be signed in to change notification settings - Fork 0
whenDomLoaded()
Eugene Lazutkin edited this page Feb 25, 2026
·
6 revisions
The whenDomLoaded() function is a utility that allows you to execute a callback function once the DOM content has fully loaded. This is particularly useful for scripts that need to manipulate the DOM after it is ready.
- Callback Management: Supports multiple callbacks that can be queued and executed once the DOM is ready.
- Automatic Handling: Automatically detects if the DOM is already loaded and executes the callbacks immediately if so.
- Event Listener: Adds an event listener for the DOMContentLoaded event if the DOM is not yet loaded, ensuring callbacks are executed at the right time.
whenDomLoaded is available as a named and default export.
whenDomLoaded(fn);-
Parameters:
-
fn: The callback function to be executed once the DOM is fully loaded. It will be called with no arguments and the return value is ignored.
-
-
Return Value: Returns
undefined.
A promise-based version of whenDomLoaded.
-
Parameters:
-
fn: The function to schedule. Ifnullorundefined, the promise resolves withundefined.
-
-
Return Value: Returns a
Promisethat resolves with the return value offn(), or rejects iffn()throws.
Removes a previously queued function from the waiting list.
-
Parameters:
-
fn: The function to remove.
-
-
Return Value: Returns
trueif the function was found and removed,falseotherwise.
To use the whenDomLoaded() function, import it into your project and pass your callback function as an argument. Here’s an example:
import whenDomLoaded, {scheduleWhenDomLoaded, remove} from 'time-queues/when-dom-loaded.js';
whenDomLoaded(() => console.log('DOM content is fully loaded!'));
// Promise-based version
const result = await scheduleWhenDomLoaded(() => document.title);
console.log('Page title:', result);
// Remove a queued callback
const myCallback = () => console.log('hello');
whenDomLoaded(myCallback);
remove(myCallback); // returns true if removed-
Callback Not Executing: Ensure that the
whenDomLoaded()function is called before the DOM content is fully loaded. If it's called afterward, the callback will execute immediately. - Multiple Callbacks: If multiple callbacks are registered, they will all execute in the order they were added once the DOM is ready. Ensure that the order of execution is as expected.
- whenLoaded() - Similar utility for full page load
- defer() - Execute callbacks in the next tick