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

三世轮回 提交于 2019-12-08 12:56:25

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11115182/javascript-code-inside-body-runs-before-scripts-in-head-are-fully-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!