What is Jquery document.ready function $(document).ready(function() in jquery and when to use it
- Document.ready function fires as soon as the DOM is loaded and ready to be manipulated by script.
- Document.ready function is the earliest point in the page load process where script can safely access element in the page's HTML DOM.
- Document.ready function events is fired before all the images, css etc.. are fully loaded.
Sample code for document ready
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
alert("Welcome");
});
});
</script>
</head>
<body>
<input type="button" value="click" id="button1">
</body>
</html>
Another way of writing (document.ready function) document ready function mentioned bellow
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function(){
$("#button1").click(function(){
alert("Welcome");
});
});
</script>
</head>
<body>
<input type="button" value="click" id="button1">
</body>
</html>
Example 1 without (document.ready function) document ready function.
Here you get to know why we use document.ready function with the bellow example.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#button1").click(function(){
alert("Welcome");
});
</script>
</head>
<body>
<input type="button" value="click" id="button1">
</body>
</html>
By the Time the Jquery Script is executed the Button Element is not loaded into the Browser DOM so the script not able to find #button1 id in the DOM, because of that the above example doesn't work.
What is the solution for that we have to use our code inside $(document).ready function so it will fully loaded all the html element so that jquery can find #button1.
Example 2 without (document.ready function) document ready function.
Placing our Jquery code just before the closing body Element.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="button" value="click" id="button1">
<script>
$("#button1").click(function(){
alert("Welcome");
});
</script>
</body>
</html>
Now By the time the jquery is executed the button element already loaded. so the above code will work without document.ready function.
Conclusion : document.ready function in Jquery ensures that, all Html element is loaded into the Browser DOM then it will execute our Jquery code.