JavaScript: Loading JavaScript before the DOM (ready event & window onload)

From The Travis van der Font Wiki
Jump to: navigation, search
This code runs after the DOM is created/loaded AND all page content is loaded (images, stylesheets subframes, audio, videos, etc):
window.onload = function ()
{
   // ...
};

// alternative using Event Listeners:
window.addEventListener('load', function ()
{
    // ....
});
This is loaded before page content BUT after the DOM is loaded:
document.addEventListener('DOMContentLoaded', function ()
{
   // ...
})
For jQuery (this is more common):
$(document).ready(function ()
{
    // ...
});

// short-hand method:
$(function ()
{
   // ...
});

Need to a ready load inside an AJAX Request?

ajaxComplete(function ()
{
    // ...
});

/***** USING JQUERY *****/

$(document).ajaxComplete(function ()
{
    // ...
});

// ### Clone of jQuery ajaxComplete() ### 

function ajaxComplete(func)
{
    (function()
    {
        const send = XMLHttpRequest.prototype.send;

        XMLHttpRequest.prototype.send = function ()
        {
            this.addEventListener('load', function ()
            {
                return func();
            });

            return send.apply(this, arguments)
        }
    })(func);
}

Reference(s)