Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about document ready block

 
James Patrick
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any difference between putting a function inside of the jQuery document ready block vs outside the block?

For example, are functions test1() and test2() equivalent in this code?

 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65227
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No practical difference. The former is kinda weird.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The functions are equivalent, but their scoping isn't--this may matter sometimes, particularly if you're not putting your functions into a non-global namespace.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65227
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right, I shoulda mentioned scope.
 
James Patrick
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, the difference in scope makes sense. Bear you said the first way was kinda weird -- sounds like putting functions outside of the document ready block is the more standard or idiomatic way to call functions?

Thanks for the help!

 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65227
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To be honest in most jQuery code, you won't see many named functions -- most are created inline unless they need to be called from multiple locations. But yeah, there's no real use case for limiting the scope of a function to the ready block -- creating two functions with the same name, one in the window scope and one in the ready handler scope, would be considered by most as a poor decision.

(Things are a bit different when writing plugins -- but that, as they say, is another show.)
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, it's weird, mostly because people don't generally define functions inside other functions, unless it's part of a module pattern. I brought it up only because it *is* a way to tuck away single-use functions without having to worry about naming.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic