I am a little confused with document.ready in jQuery.
When do you define javascript functions inside of
$(document).ready() and when do you not?
Is it safe enough just to put all javascript code inside of $(document).ready()?
What happens when you don’t do this?
For example, I use the usual jQuery selectors which do something when you click on stuff. If you don’t wrap these with document.ready what is the harm?
Is it only going to cause problems if someone clicks on the element in the split second before the page has loaded? Or can it cause other problems?
The
document.readyhandler is triggered when the DOM has been loaded by the browser and ready to be manipulated.Whether you should use it or not will depend on where you are putting your custom scripts. If you put them at the end of the document, just before the closing
</body>tag you don’t need to usedocument.readybecause by the time your script executes the DOM will already be loaded and you will be able to manipulate it.If on the other hand you put your script in the
<head>section of the document you should usedocument.readyto ensure that the DOM is fully loaded before attempting to modify it or attach event handlers to various elements. If you don’t do this and you attempt to attach for example a.clickevent handler to a button, this event will never be triggered because at the moment your script ran, the jQuery selector that you used to find the button didn’t return any elements and you didn’t successfully attach the handler.