ArticleZip > Document Ready Equivalent Without Jquery

Document Ready Equivalent Without Jquery

So, you want to know how to execute JavaScript code when the DOM is fully loaded without using jQuery? No problem! In this guide, we'll walk you through creating the equivalent of jQuery's `$(document).ready()` function using plain JavaScript.

First things first, let's understand why we need this. The `$(document).ready()` function in jQuery allows us to run a script as soon as the DOM is ready to be manipulated. While jQuery makes this easy and concise, many modern projects are moving away from using jQuery. Not to worry, we can achieve the same functionality using vanilla JavaScript.

To achieve a similar effect as `$(document).ready()`, we'll leverage the combination of the `DOMContentLoaded` event and a self-invoking function.

Javascript

document.addEventListener('DOMContentLoaded', function () {
    // Code to run when the DOM is fully loaded
    console.log('Document is ready!');
});

In the above code snippet, the `DOMContentLoaded` event is fired when the initial HTML document has been completely loaded and parsed without waiting for stylesheets, images, and subframes to finish loading. The event handler function will only execute once the DOM is fully loaded and ready to be manipulated.

By using this native JavaScript approach, you can eliminate the need for jQuery just to wait for the DOM to be ready. This is particularly useful if you are working on a project with a strict performance budget or if you want to reduce unnecessary dependencies.

To further encapsulate your code and keep the global scope clean, you can wrap your script inside a self-invoking function.

Javascript

(function () {
    document.addEventListener('DOMContentLoaded', function () {
        // Code to run when the DOM is fully loaded
        console.log('Document is ready!');
    });
})();

The self-invoking function ensures that your code is executed immediately while keeping all variables and functions within its local scope. This is a common practice to prevent naming conflicts and pollution of the global scope.

Remember, the `DOMContentLoaded` event is supported in all modern browsers, so you can rely on this method without worrying about compatibility issues.

In conclusion, you can achieve the document ready equivalent without jQuery by simply using the `DOMContentLoaded` event and a self-invoking function in native JavaScript. This approach is easy to implement, ensures better performance, and reduces unnecessary dependencies in your projects.

Give it a try in your next JavaScript project and experience the benefits of writing clean, efficient code without the need for jQuery. Happy coding!

×