Skip to content

whenDomLoaded()

Eugene Lazutkin edited this page Feb 25, 2026 · 6 revisions

Description

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.

Key features

  • 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.

Technical specifications

whenDomLoaded is available as a named and default export.

whenDomLoaded(fn);

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.

scheduleWhenDomLoaded(fn)

A promise-based version of whenDomLoaded.

  • Parameters:
    • fn: The function to schedule. If null or undefined, the promise resolves with undefined.
  • Return Value: Returns a Promise that resolves with the return value of fn(), or rejects if fn() throws.

remove(fn)

Removes a previously queued function from the waiting list.

  • Parameters:
    • fn: The function to remove.
  • Return Value: Returns true if the function was found and removed, false otherwise.

Usage instructions

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

Troubleshooting

  • 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.

See Also

  • whenLoaded() - Similar utility for full page load
  • defer() - Execute callbacks in the next tick

Clone this wiki locally