I use document ready all the time, but I’m watching some tutorial videos to really KNOW whats going on instead of just knowing from typing it so much.
I had always put it in an anonymous function out of habit as thats how its always done, but now I see if its NOT in an anonymous function (say alert(); for instance), it will execute NOT when the DOM is loaded but immediately when that javascript loads. It must be in an anonymous function for this to happen how its supposed to (when the whole page loads) and the event listeneter triggers that its ‘ready’.
Why is this?
furthermore I often see something like function(i){}(i), what does this mean?
In this answer, I’m going to use the shorthand for
$(document).ready(...), which is$(...), provided that a function is passed.The function doesn’t have to be anonymous; you can write this for example:
I think what you mean is if you try this:
It will indeed alert right away. This is because a function is expected, and
alert()is a function call. This, on the other hand, would work (albeit strangely):For your second question, what
function(i){}(i)does is declare a function object with one parameter, then immediately run it with a provided argument. This is a useful way to use an object without needing it to be global and without it needing to have a certain name. For example, this:Lets you alias
jQueryas$.