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.

+2


source to share


6 answers


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.



+4


source


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.

+4


source


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.

+1


source


You are right, there should be no problem accessing variables in other files. There might be a scale issue or a simple typo. What scope are you trying to access, and what scope are you trying to use it in?

+1


source


Yes, you can access all of the top levels. But the one you are looking for can be determined with the dom ready event, even if it is a window variable that the handler can fire after yours. Or it is in a JavaScript file that is injected dynamically.

0


source


you can set the value of a variable anywhere on the page, but it would be easier to declare them at the top of the page before the function code.

Josh

0


source







All Articles