Does javascript describe the order in the page?
So far I am calling my javascript code from jquery $ (). ready (); the function shouldn't have access to all the variables declared in my javascript code?
I have code coming from .js files and inline.
I tried to access a variable and it says it is undefined, but when I do the viewource I can see this variable.
source to share
You don't have to have access to the variable. It will really depend on the scope of the variable and where it is defined relative to where it is used. If a variable is defined in a separate ready () block, you may not have access to it, even if it is in global space, if that ready block runs after where you reference it. To be accessible, the code that defines the variable must run before the code that references it, and it must be in the same scope.
source to share
The order of the javascript really matters. Javascript runs linearly within the page, so if you have two tags <script>
:
<script src="test1.js"></script>
<script src="test2.js"></script>
test1.js
will be loaded and launched first, then test2.js
. Anything globally declared in test1.js
will be available in the second script, but not vice versa.
A side effect of this is that scripts also block when they load, so if it test1.js
took a long time to load, you will see that it will slow down the page load time. Therefore, it is recommended that you put any javascript that is not needed immediately at the bottom of your page, so that almost all the information will be displayed right before the javascript is loaded, slowing it down.
Inside the "on ready" event in jquery, you should theoretically have access to everything that was loaded as part of the DOM, as this should technically not fire before the DOM structure has been fully built.
source to share
No, you should always load Javascript in the order you want it. If you are using some jQuery plugins, you should load jQuery before these plugins, as they can instantiate an object that uses jQuery objects without your knowledge.
For my web applications, I load javascripts in the following order:
- External libraries (jQuery, Prototype, ExtJS)
- Plugins that build these libraries
- My custom javascripts
Hope my answer was helpful.
source to share