Search code examples
javascriptwindow

Only perform action if window is loaded


I want to execute a piece of code that only runs if the document has already been loaded (not something that executes RIGHT after it's loaded). Looking for something that's not JQuery.

The premise behind the question: I have a function that runs before the page is fully loaded. However, that function calls another function that dispatches an event. I only want that event to be dispatched if the window is already loaded. If not, maybe just store it in an array and dispatch it once the page has loaded


Solution

  • The nuance of your question seems to be that you aren't having trouble capturing the onload event, but rather just knowing if it's happened yet.

    I would do what jQuery does and set a flag as true inside a onload event, and then in an if statement you can reference that flag.

    For a reusable solution, you could encapsulate this behavior in a function that accepts callbacks:

    var whenLoaded = (function() {
        var isLoaded = false,
            callbacks = [];
        window.onload = function() {
            isLoaded = true;
            for (var i = 0; i < callbacks.length; i++)
                callbacks[i]();
        };
        return function whenLoaded(callback) {
            if (isLoaded) {
                callback();
            } else {
                callbacks.push(callback);
            }
        };
    })();
    
    ...
    
    whenLoaded(function() {
        // eat a cookie
    });