Skip to content

DOMContentLoaded

Marcelo de Souza Lima edited this page Jan 17, 2025 · 3 revisions

Introduction

The JsBaseClass library simplifies handling the DOMContentLoaded event by providing a built-in wrapper method called onDomContentLoaded. If your class contains this method, it will automatically be triggered when the DOM is fully loaded, eliminating the need to manually add event listeners.


How It Works

When you extend JsBaseClass and define the onDomContentLoaded method, the library internally listens for the DOMContentLoaded event using document.addEventListener. Once the DOM is ready, your onDomContentLoaded method is executed, allowing you to run initialization code that depends on the DOM being fully loaded.


Example Usage

Here’s an example of how to use the onDomContentLoaded method:

class MyApp extends JsBaseClass {
    async handle() {
        // Initialization code
        this.console.log('Your code starts here...');
    }

    async onDomContentLoaded() {
        // This method runs when the DOM is fully loaded
        this.console.log('DOM content loaded');

        // Example: Manipulate the DOM
        const header = document.createElement('h1');
        header.textContent = 'Hello, DOM is ready!';
        document.body.appendChild(header);
    }
}

// Initialize the app
window.myApp = new MyApp();
myApp.init();

Explanation

  1. handle Method:

    • This is the main initialization method of your class. It runs as soon as the class is instantiated and init is called.
    • Use this method for code that doesn’t depend on the DOM being fully loaded.
  2. onDomContentLoaded Method:

    • This method is automatically triggered when the DOMContentLoaded event fires.
    • Use this method for code that requires the DOM to be fully loaded, such as DOM manipulation or event binding.
  3. Initialization:

    • The class is instantiated and initialized using window.myApp = new MyApp(); myApp.init();.
    • The init method ensures that both handle and onDomContentLoaded are properly set up.

Output

When you run the above code, the following will happen:

  1. The handle method logs: Your code starts here....
  2. Once the DOM is fully loaded, the onDomContentLoaded method logs: DOM content loaded.
  3. A new <h1> element with the text Hello, DOM is ready! is added to the DOM.

Why Use onDomContentLoaded?

  • Simplicity: You don’t need to manually add document.addEventListener('DOMContentLoaded', ...).
  • Readability: Keeps your code clean and organized by separating DOM-dependent logic into a dedicated method.
  • Consistency: Ensures that your DOM-dependent code runs at the right time, avoiding errors caused by accessing elements before they are loaded.

Advanced Example

Here’s a more advanced example demonstrating how to use onDomContentLoaded for DOM manipulation and event binding:

class MyApp extends JsBaseClass {
    async handle() {
        // Initialization code
        this.console.log('App initialized.');
    }

    async onDomContentLoaded() {
        // DOM-dependent code
        this.console.log('DOM is ready!');

        // Add a button to the DOM
        const button = document.createElement('button');
        button.textContent = 'Click Me';
        document.body.appendChild(button);

        // Bind an event to the button
        button.addEventListener('click', () => {
            this.console.log('Button clicked!');
        });
    }
}

// Initialize the app
window.myApp = new MyApp();
myApp.init();

How It Works in Detail

  1. Class Initialization:

    • When myApp.init() is called, the handle method runs immediately.
    • The library sets up an internal listener for the DOMContentLoaded event.
  2. DOMContentLoaded Event:

    • When the DOM is fully loaded, the onDomContentLoaded method is triggered.
    • This ensures that any DOM-dependent code runs only after the DOM is ready.
  3. DOM Manipulation:

    • In the example above, a button is added to the DOM, and a click event is bound to it.
    • This is done safely within onDomContentLoaded, ensuring the button exists before the event is bound.

When to Use onDomContentLoaded

Use the onDomContentLoaded method for any code that:

  • Manipulates the DOM (e.g., adding, removing, or modifying elements).
  • Binds events to DOM elements.
  • Depends on elements being present in the DOM (e.g., querying elements with document.querySelector).

Comparison with Native JavaScript

Without JsBaseClass, you would need to manually listen for the DOMContentLoaded event:

document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM content loaded');
    // DOM-dependent code here
});

With JsBaseClass, this is simplified to:

async onDomContentLoaded() {
    this.console.log('DOM content loaded');
    // DOM-dependent code here
}

Best Practices

  1. Separate Concerns:

    • Use the handle method for non-DOM-dependent initialization.
    • Use the onDomContentLoaded method for DOM-dependent code.
  2. Avoid Blocking Code:

    • Keep both handle and onDomContentLoaded methods lightweight to avoid blocking the main thread.
  3. Leverage Logging:

    • Use this.console for structured logging, making it easier to debug your code.

Example Output in Console

App initialized.
DOM is ready!

By using the onDomContentLoaded method, you can ensure that your DOM-dependent code runs at the right time, making your applications more robust and easier to maintain. 🚀

Clone this wiki locally