Why is $(document).ready
needed after the tag?
What would happen if we don\'t use $(document).ready
?
Why is
$(document).ready
really need aftertag when we use javascript.
It isn't.
What else if we don't use
$(document).ready
First, understand why people use ready
: It's used to delay the code within the function you pass into it until jQuery calls that function, which jQuery does when it thinks the document is fully loaded.
JavaScript code within script
tags runs immediately. If the script
tag is above an element it refers to, the element won't exist when the script runs:
That div
will not be shown, because it doesn't exist when the code runs. So people use ready
to delay their code.
There's a better way if you control where your script
tags go: Just put your script
tag at the end of the document, just before the closing
tag:
All of the elements defined above the script
tag will exist when the code runs. No need for ready
.