How many JavaScript programs are executed for a single web-page in the browser?

不羁岁月 提交于 2019-11-27 17:06:15

Dmitry Soshnikov has answered your question. Every <script> element is executed as a Program, as defined by the ECMAScript specification. There is one global object that each Program within a single page uses. And that's really it.

Function hoisting — the process that evaluates function statements before the rest of the function — is part of the ECMAScript standard IIRC (I can't find a reference right now, but I recall seeing discussions of EMCAScript that mention it). The evaluation of script tags is part of the HTML standard. It does not specify that they are "separate programs" in so many words, but it does say that the script elements are evaluated in the order they appear in the document. That is why functions in later script tags aren't hoisted: The script hasn't been evaluated yet. That also explains why one script stopping doesn't cut off subsequent scripts: When the current script stops evaluating, the next one starts.

They are separate programs, but they modify a shared global object.

Another way to think about this is pseudo local vs global scope. Every SCRIPT declaration has a local scope to it's current methods/functions, as well as access to the current (previously declared) global scope. Whenever a method/function is defined in a SCRIPT block, it is then added to the global scope and becomes accessible by the SCRIPT blocks after it.

Also, here's a further reference from W3C on script declaration/handling/modification:

The dynamic modification of a document may be modeled as follows:

  1. All SCRIPT elements are evaluated in order as the document is loaded.
  2. All script constructs within a given SCRIPT element that generate SGML CDATA are evaluated. Their combined generated text is inserted in the document in place of the SCRIPT element.
  3. The generated CDATA is re-evaluated.

This is another good resource on script/function evaluation/declaration.

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