Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
asynckeyword when calling asynchronous functions - Use
awaitto wait for promises to resolve - Wrap async operations in try/catch for error handling
-
DOMContentLoadedfires earlier thanonload
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.
Advertisements
