HTML文档头部的外部脚本是否保证在包含在主体中的脚本之前执行? [英] Are external scripts in the head of an HTML document guaranteed to execute before scripts contained within the body?

查看:54
本文介绍了HTML文档头部的外部脚本是否保证在包含在主体中的脚本之前执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在HTML页面中尽可能早地执行一些内联​​javascript,以便在外部.js文件中使用库函数。

I'm trying to execute some inline javascript within an HTML page as early in page processing as possible that makes use of library functions in an external .js file.

虽然我总是看到将库脚本放在头脑中,并且正文中的客户端脚本似乎正常工作,但我无法在任何地方找到文档文档头部中包含的外部脚本保证在脚本位于文档正文之前运行(w3schools网站除外,但它们不算作有信誉的参考)

While I've always seen that putting library scripts in the head, and client scripts in the body just seems to work, I can't find documentation anywhere that says that external scripts included within the head of a document are guaranteed to run before script located within the body of a document (except on the w3schools site, but they don't count as a reputable reference)

为了说明,我想知道HTML的用户代理行为如下所示:

To illustrate, I'm wondering about the User-Agent behavior for HTML that looks like this:

<html>
   <head>
      <script type="text/javascript src="libraryModule.js"></script>
   </head>
   <body>
      <script type="text/javascript">
         // is this guaranteed to run after the external script?
         // or is it possible this module that the external library
         // adds to the global namespace won't be there yet?
         var result = ModuleInExternalLibrary.DoLibraryThing();
      </script>
   </body>
</html>

这是否记录在任何地方?我在W3C规范中找不到任何内容或任何总结的好帖子在所有主要浏览器的这个区域中的行为。请提供一个链接。

Is this documented anywhere? I can't find anything in the W3C spec or any good post that sums up the behavior in this area of all the major browsers. Please provide a link.

我不得不等到onload事件触发才能保证外部脚本已执行?

Am I stuck having to wait until the onload event fires in order to guarantee that external scripts have executed?

推荐答案

出现在< script> 之间的JavaScript语句和< / script> 标签按外观顺序执行。所以是的,它是有保证的,除非你正在做一些聪明的事情,如延期加载或类似的东西。

JavaScript statements that appear between <script> and </script> tags are executed in order of appearance. So yes, it is guaranteed, unless you are doing something clever like deferred loading or something similar.

执行JavaScript程序

这篇关于HTML文档头部的外部脚本是否保证在包含在主体中的脚本之前执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆