Is a modern equivalent of $document.ready() still required in Vanilla JS apps?

Viewed 2501

When I learnt JavaScript a few years back, jQuery was still considered good standard practice, and it was recommended that the main application code be called from the $document.ready() event handler, so as to ensure the DOM was safe to use.

Fast forward a few years since the last time I worked on JavaScript, and the consensus nowadays seems to be to avoid jQuery. Also, since scripts are usually loaded at the very end of the HTML document, it seems that $document.ready() might not be needed any longer.

In question $(document).ready equivalent without jQuery I see several modern alternatives for this piece of code. However, it is still not clear to me whether including any one of these is considered standard practice or recommended, in general.

So my question is about current practice: should I always include such code as the entry point of a Vanilla JS application, or, on the contrary, is it considered now safe to start loading the JS app without any wrappers?

1 Answers

An equivalent is DOMContentLoaded event

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

Source : https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM fully loaded and parsed');
});

To address the last part of your question, I'd say "Yes !" ^^

You can define your custom functions outside of this "main function" scope, but wait for the event to be completed before doing anything with the DOM.

Related