Executing code when a page loads - traditional vs modern approaches.
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<h1>HTML DOM Events</h1>
<h2>The onload Event</h2>
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</body>
</html>
Click the button above to simulate the page load event...
onload attribute mixes HTML and JavaScript<!DOCTYPE html>
<html lang="en">
<head>
<title>Modern Page Load</title>
</head>
<body>
<h1>HTML DOM Events</h1>
<h2>The DOMContentLoaded Event</h2>
<p id="status">Waiting for page to load...</p>
<script>
// Modern approach - runs as soon as DOM is ready
document.addEventListener('DOMContentLoaded', () => {
const statusElement = document.getElementById('status');
// Show loading state
statusElement.textContent = 'Loading...';
statusElement.style.color = '#ff9800';
console.log('DOM is ready! Starting initialization...');
// Simulate initialization work with a delay
setTimeout(() => {
statusElement.textContent = 'Page loaded successfully!';
statusElement.style.color = 'green';
statusElement.style.fontWeight = 'bold';
console.log('Initialization complete!');
}, 1500);
});
</script>
</body>
</html>
Click the button above to simulate the page load event...
addEventListener with arrow functionsonload attribute in the <body> tagDOMContentLoaded event with addEventListenerDOMContentLoaded for better performanceDOMContentLoaded fires faster than window.onload (doesn't wait for images)console.log instead of alerts for development feedback💡 Pro Tip:
The DOMContentLoaded event fires when the HTML document has been completely parsed, without waiting for stylesheets, images, and subframes to finish loading. This means your JavaScript can start executing faster, improving perceived page performance!
DOMContentLoaded when you need to manipulate the DOM as soon as possible. Use window.addEventListener('load', ...) only if you need to wait for all resources (images, stylesheets) to load completely.