Immediately Invoke a Javascript Function

This function executes immediately on DOM ready. No need to write window.onload = function. Just place this type of function near the end of your code and it will automatically execute when the page starts.

(function() {
    // add code here
})();

Example:

(function(){
    a=document.createElement('script');
    a.type='text/javascript';a.async=true;
    a.src="e.js";
    var b=document.getElementsByTagName('script')[0];
    b.parentNode.insertBefore(a,b);
})();

This particular example dynamically creates the script tag to load a javascript file, which in this example is "e.js". This is executed immediately after the page has loaded.

However, it doesn't need to be used for loading scripts, it can also execute code or another predefined function.

Another way to do this is to use window.onload...

window.onload = function(){
    console.log("This anonymous function was just executed.");
}

// compared to ...

(function(){
    console.log("This anonymous function was just executed.");
})();
Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use