I am referencing JavaScript as follows on an HTML page:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&region=GB"></script>
<script type="text/javascript" src="js/shared.js"></script>
<script type="text/javascript">
$('document').ready(function() {
// In-page code: call some functions in shared.js
});
</script>
The functions defined in shared.js are not wrapped inside $('document').ready. So:
-
Is it safe to assume that functions defined in
shared.jsare available to the “in-page code”? -
If I pull out the in-page code into a separate file called
local.js(keeping it wrapped in$('document').ready), is it still safe to assume that functions defined inshared.jsare available? -
Finally, is the fact that I’m not wrapping shared.js inside
$('document').readya problem? I’m finding that if I do wrap it, its functions are no longer available to the in-page code.
The reason for question 3 is that I’m hitting this problem: Uncaught TypeError: Property … is not a function – after page has loaded
and wondering if it is something to do with how I’ve organised my code.
UPDATE: Thanks for the answers. It’s now clear that using $('document').ready in shared.js would remove those functions from global scope. However, I just want to clarify the original question in point 3.
Can I assume that if I do the following:
- inside my in-page code, loaded inside
$('document').ready, call a function from shared.js - have the function in shared.js refer to jQuery, Google Maps, or elements on my page
there will be no problems?
In other words, is it safe to assume that the page will have loaded by the time the functions inside shared.js are called, even if I’m not wrapping everything in that file inside $('document').ready?
Yes, As long as those functions are injected into global scope
Yes, As long as
local.jsis included aftershared.jsAND shared.js injects functions into global scope.Wrapping functions in
document.readytakes them outside of global scope.You need to inject variables in global scope, this is as easy as doing