Try it here
Subscribe
onload Event

Javascript/Jquery onload event

javascript/jquery_onload_event

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()">

Examples:

In HTML:

<element onload="myScript">
<iframe onload="myFunction()" src="/default.asp"></iframe>

<p id="demo"></p>

In JavaScript:

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>

In JavaScript, using the addEventListener() method:

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>

JQuery:

$( document ).ready()

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!" );
});

Shorthand for $( document ).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 );

Writer profile pic

Arun on Apr 04, 2015 at 12:04 am


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.



Post Comment

Comments( 0)

×

Forgot Password

Please enter your email address below and we will send you information to change your password.