There are different ways to check if document is ready in jquery.
We always want all the document elements to be accessible before performing any sort of action on them. In order to do so we need to check if DOM
is ready or not.
Only check if DOM
is ready
If only want to know that your html elements are parsed and they are ready to access. Then you can do so by below methods.
Javascript
We can listen to DOMContentLoaded
event on the window
to check if document object model is ready or not.
window.addEventListener('DOMContentLoaded', function(){ document.querySelector('#learnersbucket').innerHTML = 'You are awesome'; });
Jquery
//First way $(document).ready(function(){ $('#learnersbucket').text('You are awesome'); }); //second way $(function(){ $('#learnersbucket').text('You are awesome'); });
Check if whole page is ready
If you want to make sure that your html is completely loaded and all your other assets like Css, Images, Fonts, Video, Audio etc are loaded as well then you should use the below methods.
Javascript
We can listen to load
event on the window
to check if everything is loaded or not.
window.addEventListener('load', function(){ // Everything has loaded! document.querySelector('#learnersbucket').innerHTML = 'You are awesome'; });
We can also check if specific elements are loaded or not. But remember your DOM
should be ready in order to select the elements.
document.querySelector('#image').addEventlistener('load', function(){ //Image is loaded });
Jquery
$(window).load(function(){ alert('Window is loaded completely'); });