且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

确保首先运行Javascript脚本?

更新时间:2023-12-05 11:58:34

我注意到某些脚本似乎先于某些脚本被调用 页.我想知道,脚本加载的具体顺序是什么?

I've noticed some scripts seem to be called before others on a certain page. I was wondering, what is the specific order for scripts to load?

这是由W3C在其语言规范中设置的.例如,对于 HTML 4.01规范,它是在

This is set by W3C in their language specifications. For the HTML 4.01 Specification, for instance, it's defined in Section 18.2.4 Dynamic modification of documents, item 1.

引用了.js脚本之前的页内?

In-page before referenced .js scripts?

请参见上文.不,内联脚本和链接脚本的处理方式相同.

See above. No, inline and linked scripts are handled identically.

它们是按照从页面上第一个提及到最后一个的顺序运行的吗? 还是依赖于浏览器?

Are they run in order from first mentioned to last in page, or is this browser-dependent?

规范要求它们从上到下依次运行.您将必须找到根据规范实现该语言的浏览器.我现在无法想到以不同的方式处理SCRIPT标签的方法,但是我敢肯定这是可能的.

The specifications call for them to be run sequentially from top to bottom. You'll have to find a browser that implements the language according to specification. I can't think of any right now that handle SCRIPT tags differently, but I'm sure that is possible.

要考虑的另一件事是运行"的定义.这听起来像是语义解析,但事实并非如此.像任何编程语言一样,JavaScript本身也被设计为按照标准运行.在 ECMA-262 5.1版/2011年6月中指定了JavaScript标准,以在第7节词汇约定"中从左到右进行评估. (行尾被视为下一行的最左字符.)本文档还提供了对语句和其他操作(例如WHILE或FOR语句)的求值顺序的约定.

Another thing to consider is the definition of "run." That may sound like semantic parsing, but it's not. JavaScript, like any programming language, is itself designed to behave according to standards. JavaScript is specified in the ECMA-262 5.1 Edition / June 2011 standard to evaluate from left-to-right in Section 7 Lexical Conventions. (Line endings are treated as the left-most character of the next line.) This document also provides conventions for the order in which statements and other operations are evaluated, such as WHILE or FOR statements.

如何确保某个特定脚本首先在页面中运行?

How can one make sure that a specific script is first to run in a page?

(1)将其放在顶部,(2)选择一个实现语言规范的浏览器.

(1) Put it at the top, and (2) choose a browser that implements the language specification.

但是,我觉得这个问题可能还有其他问题.如果试图阻止意外代码执行,则必须阻止它,直到ONLOAD事件处理程序注册该页面完成为止. (将您的操作简单地封装在一个函数中,或者用IF包围它们以检查是否有布尔标志,即isLoaded由ONLOAD设置为true.)然后,当ONLOAD事件处理程序触发时,您可以按自己的时间表启动操作而无需不必担心诸如未实例化的DOM对象之类的事情.

However, I feel there may be something more behind this question. If you're trying to stop unexpected code from executing, you'll have to block it until the ONLOAD event handler registers that the page is complete. (Simply enclose your operations in a function or surround them with an IF to check for a boolean flag, i.e. isLoaded being set true by ONLOAD.) Then, when the ONLOAD event handler fires off, you can kick off operations on your own schedule without having to worry about things like uninstantiated DOM objects.