Hello @kartik,
There are three options:
- If script is the last tag of the body, the DOM would be ready before script tag executes
- When the DOM is ready, "readyState" will change to "complete"
- Put everything under 'DOMContentLoaded' event listener
onreadystatechange
document.onreadystatechange = function () {
if (document.readyState == "complete") {
// document is ready. Do your stuff here
}
}
DOMContentLoaded
document.addEventListener('DOMContentLoaded', function() {
console.log('document is ready. I can sleep now');
});
Concerned about stone age browsers: Go to the jQuery source code and use the ready function. In that case you are not parsing+executing the whole library you're are doing only a very small part of it.
Thank You!!