ReedyBear's Blog

Execute script after DOMContentLoaded, or immediately if the event has already fired

MDN Recommends defining a named function, and using an if (readyState==='loading') check, which is fine.

I wanted a shorthand that does not require you to name your function, and came up with this:

(document.readyState === "loading"  
    ? document.addEventListener.bind(this,'DOMContentLoaded')  
    : function(f){f();}.bind(this)  
).call(this,  
    /** the function you actually care about */  
    function(){  
        console.log("hey, my script works all the time!");  
    }  
);  

#code