-
-
Notifications
You must be signed in to change notification settings - Fork 0
whenLoaded()
Eugene Lazutkin edited this page Mar 10, 2026
·
7 revisions
The whenLoaded() function is a utility that allows you to execute a callback function once the page is fully loaded (including images, stylesheets, and other resources). It helps manage functions that need to wait for all page resources to be available before executing.
- Callback Management: Supports multiple callbacks that can be queued and executed once the page is fully loaded.
- Automatic Handling: Automatically detects if the page is already loaded and executes the callbacks immediately if so.
- Event Listener: Adds an event listener for the load event if the page is not yet loaded, ensuring callbacks are executed at the right time.
whenLoaded is available as a named and default export.
whenLoaded(fn);-
Parameters:
-
fn: The callback function to execute once the page is fully loaded (all resources). It will be called with no arguments and its return value is ignored.
-
-
Return Value: Returns
undefined.
A promise-based version of whenLoaded.
-
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 whenLoaded() function, import it into your project and pass your callback function as an argument. Here’s an example:
import whenLoaded, {scheduleWhenLoaded, remove} from 'time-queues/when-loaded.js';
whenLoaded(() => console.log('Document is fully loaded!'));
// Promise-based version
const result = await scheduleWhenLoaded(() => document.title);
console.log('Page title:', result);
// Remove a queued callback
const myCallback = () => console.log('hello');
whenLoaded(myCallback);
remove(myCallback); // returns true if removed-
Callback Not Executing: Ensure that the
whenLoaded()function is called before the page 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 page is fully loaded.
- whenDomLoaded() - DOM content loaded utility
- defer() - Execute on next tick