[英]Do browsers read/store everything in a Javascript file or only the stuff they need?
Here's what I'm asking: 这是我要问的:
Suppose I have on my site 假设我在我的网站上
<script type="text/javascript" src="global.js"></script>
<script type="text/javascript">
someFunction();
someOtherFunction();
</script>
and suppose someFunction
and someOtherFunction
are the only functions used on the page and are 2 of 10,000 functions in global.js
. 并假设
someFunction
和someOtherFunction
是页面上唯一使用的函数,并且是global.js
中10,000个函数中的2个。 Clearly the browser would be better off in this situation looking only for those 2 functions in global.js
and skipping everything that doesn't depend on them, but which of the following ways is actually how the browser parses JS? 显然,在这种情况下浏览器会更好,只在
global.js
查找这两个函数,并跳过不依赖它们的所有内容,但是浏览器实际上是通过以下哪种方式解析JS的呢?
1. 1。
<script type="text/javascript" src="global.js"></script>
Load entire text source of global.js into memory. 将global.js的整个文本源加载到内存中。 Parse and execute any JavaScript code there in the current global environment.
在当前的全局环境中解析并执行所有JavaScript代码。
2. 2。
<script type="text/javascript"> someFunction(); someOtherFunction(); </script>
Look in the current global environment for the function named someFunction()
and call it. 在当前全局环境中查找名为
someFunction()
的函数,然后调用它。 Next look in the current global environment for the function named someOtherFunction()
and call it. 接下来,在当前全局环境中查找名为
someOtherFunction()
的函数并调用它。 Has absolutely no clue about where or how they were defined. 完全不知道在哪里或如何定义它们。
All in all, browsers will take the entire file and parse and execute all of the contained code there up front because that is the design of the language. 总而言之,浏览器将获取整个文件并解析并执行所有包含的代码,因为这是该语言的设计。 It will not look forward or "compile" all of the JavaScript code in a page at once.
它不会一次浏览或“编译”页面中的所有JavaScript代码。
This is a great question! 这是一个很好的问题!
As an answer to your question, #1 is the most correct, as indeed all functions are parsed by the interpreter during script load, rather than just those referenced by your containing script. 为了回答您的问题, #1是最正确的,因为实际上所有功能都是在脚本加载期间由解释程序解析的,而不是仅由您包含的脚本引用的那些功能解析。
First off, as soon as the include statement executes the entire JS file is loaded into the client's browser cache. 首先,一旦include语句执行, 整个JS文件就会加载到客户端的浏览器缓存中。 At that point global.js is parsed , interpreted and executed by your browser's Javascript engine.
那时,由浏览器的Javascript引擎解析 , 解释和执行 global.js。 Any global functions and variables declared in global.js will then be able to be used by the containing script.
然后,包含脚本可以使用global.js中声明的所有全局函数和变量。
It is important to note, however, that no Javascript is ever compiled into machine code, rather it is lexically parsed and interpreted according to ECMA standards. 重要的是要注意,但是,从来没有Java脚本被编译成机器代码,而是根据ECMA标准对其进行了词法分析和解释 。
For more information on script loading, check out this great resource on html5rocks: Script Loading 有关脚本加载的更多信息,请在html5rocks上查看以下重要资源: 脚本加载
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.