Wednesday 18 September 2013

$( document ).ready() - The first thing in jQuery

Hi Everyone, The first thing to learn about jQuery is $( document ).ready(): If you want an event to work on your page , you should call it inside the $(document).ready() function.

Diff between $( window ).load() and $(document).ready()

$( document ).ready() will only load once the page Document Object Model (DOM) is ready for JavaScript code to execute and before the page contents are loaded.

$( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.
1
2
3
$( document ).ready(function() {
    console.log( "DOM is ready!" );
})


If you want to use shorthand for $( document ).ready(). below shown is best to use the long form.
1
2
3
4
// Shorthand for $( document ).ready()
$(function() {
    console.log( "DOM is ready!" );
});

As well you can also pass a named function to $( document ).ready() instead of passing an anonymous function. likw shown below,
1
2
3
4
function onReadyFn() {
 // Code to run when the document is ready.
} 
$( document ).ready( onReadyFn );

The below example shows $( document ).ready() and $( window ).load() in action.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
    $( document ).ready(function() {
        console.log( "Document is Ready..." );
    });
 
    $( window ).load(function() {
        console.log( "Window Loaded Successfully..." );
    });
    </script>
</head>
<body>
    <iframe src="http://jqueryexamples4u.blogspot.in/"></iframe>
</body>
</html>

No comments:

Post a Comment