Run jQuery on DOM loaded

vicnumb Oct 27, 2012

Oct 27 2012 Published by under jQuery & JavaScript

When writing first jQuery lines of code, the most common error is not taking into consideration the page content loading. Developers try to perform actions over the page content that is not loaded yet. Then spending days trying to find out why their code might not work.

There are 2 solutions of this problem

 

1. Placing the jQuery code right before the closing body tag. This way jQuery will always run after the entire page content is loaded so will be able to perform operations over page html/css code.

 

2. Adding the jQuery code $(document).ready() inside the head tag
This way we tell jQuery to run the script after website is loaded.

a)jQuery on DOM loaded normal code

<script>
$(document).ready(function() {
    // your jQuery code here
});
</script>

b) jQuery on DOM loaded short code

<script>
$(function() {
    // your jQuery code here
});
</script>

 

Both examples work same way, the first one is more readable for beginners, while the second one is faster to write.

Example:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script>
        $(function() {
            setTimeout(function(){
                $("span").text("5 Seconds are gone. Content loaded and jQuery functions running!");
            }, 5000);
        });
    </script>
 
</head>
<body>
	<span>Wait 5 Seconds after page  content is loaded.</span>
</body>
</html>

No responses yet

Leave a Reply