简体   繁体   中英

Javascript code inside <BODY> runs *before* <SCRIPT>s in <HEAD> are fully loaded?

When I use the minified version ( ext-all.js ) everything is fine but when I replace it with ext-all-debug.js (everything else intact), firebug reports all sorts of errors due to undefined values that I know are defined in either Ext or other js files that I load after Ext.

After some trial and error, I put console.log() s at the end of few js files and none shows up. I think using ext-all-debug.js somehow causes the js code in <BODY></BODY> to be executed before the scripts in the <HEAD> are fully loaded and this results in "undefined" errors because the code in the <BODY> references values that are supposed to be loaded beforehand.

right ?

<HEAD>
<SCRIPT type="text/javascript" src="ext/ext-base.js"></SCRIPT>
<SCRIPT type="text/javascript" src="ext/ext-all-debug.js"></SCRIPT>
<SCRIPT type="text/javascript" src="my_lib.js"></SCRIPT> <!-- defines myValue -->
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
console.log(myValue) // undefined
</SCRIPT>
</BODY>

here is my_lib.js

var myValue = 10;
console.log("my_lib.js loaded");

And

my_lib.js loaded

does not show up in the console.

As long as scripts aren't marked defer or async or loaded dynamically, they will execute in the order that they are encountered in the HTML file. That is part of the spec so it's guaranteed.

If you are seeing myValue as undefined after you think you've defined it in an earlier script, then there is some other problem.

Some possibilities are:

  1. One of your scripts has an error that prevents full execution.
  2. Your variable isn't getting defined in the global scope, but rather some sub-scope so it isn't available at the global scope when you try to use it.
  3. Your variable is defined by the previous script, but not successfully initialized to have a value other than undefined .
  4. Your scripts aren't being found by the browser (and thus not loading/executing).

If you can show us a working/non-working page that exhibits the problem, we can likely spot the issue quickly. As it is now with no sample page that shows the issue, we can only speculate on possible causes.

I figured it out. Appears that (my) ext-all-debug.js is buggy. After inspecting it in PhpStorm, I found few syntactic errors and fixed them. Everything works fine now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM