aspose file tools*
The moose likes HTML, CSS and JavaScript and the fly likes Question about document ready block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Question about document ready block" Watch "Question about document ready block" New topic
Author

Question about document ready block

James Patrick
Greenhorn

Joined: Feb 07, 2010
Posts: 5
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

Joined: Jan 10, 2002
Posts: 61654
    
  67

No practical difference. The former is kinda weird.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

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

Joined: Jan 10, 2002
Posts: 61654
    
  67

Right, I shoulda mentioned scope.
James Patrick
Greenhorn

Joined: Feb 07, 2010
Posts: 5
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

Joined: Jan 10, 2002
Posts: 61654
    
  67

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

Joined: Sep 29, 2008
Posts: 12617

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question about document ready block