-1

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

  • 3
    https://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery – Jack Jul 14 '16 at 20:08
  • Are you trying to detect an event or just have some code to put in an `if` statement? – 4castle Jul 14 '16 at 20:15
  • Basically put in an `if` statement. I've tried DOMContentLoaded and onload, but they don't work with what I'm doing. I want a check to see if the dom is loaded, not to run something right after it's been loaded... if that makes sense – Hassaan Hafeez Jul 14 '16 at 20:23

1 Answers1

1

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
});
4castle
  • 28,713
  • 8
  • 60
  • 94
  • 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. – Hassaan Hafeez Jul 14 '16 at 21:07
  • @HassaanHafeez I've updated my answer so that it will be more multipurpose with an IIFE, but essentially you just need to put that statement in an `onload` block or yes, otherwise put it in an array to be called later. – 4castle Jul 14 '16 at 22:36