JavaScript - event fired when all web page is loaded
Quick solution:
xxxxxxxxxx
// Events that wait for all resources
// 1.
window.addEventListener('load', function() { /* ... */ });
// 2.
// <body onload="executeSomeLogic()"></body>
// 3.
document.body.onload = function() { /* ... */ };
// Events that do not wait for all resources
// 1.
window.addEventListener('DOMContentLoaded', function() { /* ... */ });
// 2.
document.addEventListener('DOMContentLoaded', function() { /* ... */ });
Note: read this article to know about load event order.
Below the events usage are presented in details.
This event is called when body element is ready, scripts executed and all synchronous resources are loaded (frames, objects, images, etc.).
xxxxxxxxxx
<html>
<body onload="onBodyLoad()">
<p>Some text ...</p>
<script>
function onBodyLoad() {
console.log('Body onload event called.');
}
</script>
</body>
</html>
This event is called when body element is ready, scripts executed and all synchronous resources are loaded (frames, objects, images, etc.).
document.body
property used in below example is not avaialbe until body
element is created - access it from inside body element.
xxxxxxxxxx
<html>
<body>
<p>Some text ...</p>
<script>
document.body.onload = function() {
console.log('Body onload event called.');
}
</script>
</body>
</html>
This event is called when whole web page is ready, scripts executed and all synchronous resources are loaded (frames, objects, images, etc.).
xxxxxxxxxx
<html>
<head>
<script>
window.onload = function() {
console.log('Window onload event called.');
};
</script>
</head>
<body>
<p>Some text ...</p>
</body>
</html>
xxxxxxxxxx
<html>
<head>
<script>
window.addEventListener('load', function() {
console.log('Window onload event called.');
});
</script>
</head>
<body>
<p>Some text ...</p>
</body>
</html>
This event occurs when the DOM is ready without waiting to load for the stylesheets, images and subframes.
Note: this approach is not supported in Iinternet Explorer and Opera < 9.
xxxxxxxxxx
<html>
<body>
<p>Some text ...</p>
<script>
window.addEventListener('DOMContentLoaded', function() {
console.log('Window DOMContentLoaded event called.');
});
document.addEventListener('DOMContentLoaded', function() {
console.log('Document DOMContentLoaded event called.');
});
</script>
</body>
</html>