The onload event occurs when an object has been loaded.
onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
Execute a JavaScript immediately after a page has been loaded:
<body onload="OnloadFunction()">
<element onload="myScript">
<iframe onload="myFunction()" src="/default.asp"></iframe> <p id="demo"></p>
object.onload = function(){myScript};
<iframe id="myFrame" src="/default.asp"></iframe> <p id="demo"></p> <script> document.getElementById("myFrame").onload = function() {myFunction()}; function myFunction() { document.getElementById("demo").innerHTML = "Iframe is loaded."; } </script>
object.addEventListener("load", myScript);
<iframe id="myFrame" src="/default.asp"></iframe> <p id="demo"></p> <script> document.getElementById("myFrame").addEventListener("load", myFunction); function myFunction() { document.getElementById("demo").innerHTML = "Iframe is loaded."; } </script>
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.
// A $( document ).ready() block. $( document ).ready(function() { console.log( "ready!" ); });
$(function() { console.log( "ready!" ); });
You can also pass a named function to $( document ).ready() instead of passing an anonymous function.
Passing a named function instead of an anonymous function.
function readyFn( jQuery ) { // Code to run when the document is ready. } $( document ).ready( readyFn ); // or: $( window ).on( "load", readyFn );
This article is contributed by Arun. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.