Before moving onto the use of onload event first we should make ourselves familiar with the iframe tag.
The iframe tag can be used to create embedded web pages which are displayed inside a bordered rectangular region on the host webpage. iframe tag can take different attributes such as the src attribute to specify the URL of the webpage and the height and width attributes for the size of the embedded webpage:
Now that we have made ourselves familiar with the iframe tag we will take a look at how we can implement an onload event on it.
Implementing an onload Event in iframe in JavaScript
There are several different methods which can be used to implement the onload event. The easiest way is through the onload attribute which can be used directly with the iframe tag.
onload Attribute
<html>
<body>
<center>
<h1>Implementing onload Event in iframe in JavaScript</h1>
<iframe src="https://linuxhint.com/" height="500px" width="40%" onload="displayMessage()"></iframe>
</center>
</body>
<script>
function displayMessage() {
alert("Page Loaded Successfully!");
}
</script>
</html>
addEventListener() Method
The second method is by adding an event listener to the iframe tag:
<html>
<body>
<center>
<h1>Implementing onload Event in iframe in JavaScript</h1>
<iframe id="linuxHint" src="https://linuxhint.com/" height="500px" width="40%" onload="displayMessage()"></iframe>
</center>
</body>
<script>
var page = document.getElementById("linuxHint");
page.addEventListener("load", displayMessage)
function displayMessage() {
alert("Page Loaded Successfully!");
}
</script>
</html>
JavaScript onload Event
The third and the last method is by using the onload event directly on the iframe object in JavaScript:
<html>
<body>
<center>
<h1>Implementing onload Event in iframe in JavaScript</h1>
<iframe id="linuxHint" src="https://linuxhint.com/" height="500px" width="40%" onload="displayMessage()"></iframe>
</center>
</body>
<script>
var page = document.getElementById("linuxHint");
page.onload = function () {
alert("Page Loaded Successfully!");
}
</script>
</html>
Conclusion
This guide has listed three different methods of implementing the onload event in the iframe tag in JavaScript methods. The onload events can be used to run scripts after the contents of the webpage have been loaded.