In jQuery you can have multiple calls for the various page and other events, like so:
$(document).ready(function() {
And you can add multiple ‘ready’ function definitions along the way, you’re not limited to only one. Of course this helps by keeping code defined close to where it’s being used.
My question is, if in one of the document.ready function declarations I declare a local variable using var, will it be available in another document.ready function declaration that’s also used by the page?
I’m not sure how jQuery works in circumstances like these; whether it weaves the various functions’ scopes together somehow or if each of those functions runs in standalone fashion when the ready event is fired, each having no idea about the others’ variables. (I’d guess the second.)
No, they’re local variables to the function you’re passing into
document.ready.And you’d be right. 🙂 In fact, jQuery can’t comingle the execution contexts of the functions, those are managed by the JavaScript engine.
You can make them all share a parent execution context, though, by putting them all in a container function:
I don’t think I’d advocate having multiple
readyhandlers (or even one, really) unless you’re writing a library. But that’s a different topic.