Calling asynchronous code from index.html page in JavaScript?

Calling asynchronous code when an HTML page loads requires using async/await with event handlers. This allows you to run asynchronous operations during page initialization.

Using onload with Async Function

The most straightforward approach is to use the onload attribute with an async function:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Async Code on Page Load</title>
</head>
<body onload="initPage()">
    <h1>Async Page Loading Example</h1>
    <div id="output"></div>

    <script>
        async function initPage() {
            console.log("Page loading started...");
            await fetchData();
            await processData();
            console.log("Page loading completed!");
        }

        async function fetchData() {
            return new Promise(resolve => {
                setTimeout(() => {
                    console.log("Data fetched successfully");
                    document.getElementById('output').innerHTML = "Data loaded!";
                    resolve();
                }, 2000);
            });
        }

        async function processData() {
            return new Promise(resolve => {
                setTimeout(() => {
                    console.log("Data processed successfully");
                    resolve();
                }, 1000);
            });
        }
    </script>
</body>
</html>
Page loading started...
Data fetched successfully
Data processed successfully
Page loading completed!

Using DOMContentLoaded Event

A more modern approach uses the DOMContentLoaded event listener:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOMContentLoaded Async Example</title>
</head>
<body>
    <h1>Modern Async Loading</h1>
    <div id="status">Loading...</div>

    <script>
        document.addEventListener('DOMContentLoaded', async () => {
            console.log("DOM loaded, starting async operations");
            
            try {
                await loadUserData();
                await initializeComponents();
                document.getElementById('status').innerHTML = "Ready!";
            } catch (error) {
                console.error("Loading failed:", error);
                document.getElementById('status').innerHTML = "Error loading page";
            }
        });

        async function loadUserData() {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    console.log("User data loaded");
                    resolve({name: "John", role: "admin"});
                }, 1500);
            });
        }

        async function initializeComponents() {
            return new Promise(resolve => {
                setTimeout(() => {
                    console.log("Components initialized");
                    resolve();
                }, 800);
            });
        }
    </script>
</body>
</html>
DOM loaded, starting async operations
User data loaded
Components initialized

Comparison of Approaches

Method Timing Modern? Error Handling
onload After all resources load Traditional Basic
DOMContentLoaded After DOM is ready Yes Better with try/catch

Key Points

  • Always use async keyword when calling asynchronous functions
  • Use await to wait for promises to resolve
  • Wrap async operations in try/catch for error handling
  • DOMContentLoaded fires earlier than onload

Conclusion

Use async/await with either onload or DOMContentLoaded to call asynchronous code from HTML. The DOMContentLoaded approach is more modern and provides better error handling capabilities.

Updated on: 2026-03-15T23:18:59+05:30

322 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements