简体   繁体   English

HTML 异步脚本何时*完成*执行?

[英]When do HTML async scripts *finish* executing?

There is a lot of documentation about how async and defer affect the timing of the loading and the start of execution of external scripts, but I can't find anything that mentions when the script finishes executing.有很多关于asyncdefer如何影响加载时间和外部脚本执行开始的文档,但我找不到任何提到脚本完成执行时的内容。

For instance, suppose the external script defines functions one() , two() , three() , and four() :例如,假设外部脚本定义了函数one()two()three()four()

<head>
    …
    <script async="async" src="…"></script>
    …
</head>

<body>
    …
    <script> window.onload="one()" </script>
        …
    <script> two() </script>
</body>

<script> three() </script>

</html>

<script> four() </script>

The external script starts loading in parallel with the HTML, and then executes as soon as it's loaded.外部脚本开始与 HTML 并行加载,然后在加载后立即执行。

I'm pretty sure that two() is unrealiable, as it could be undefined when it gets called, but I don't know about the others.我很确定two()是不可靠的,因为它在被调用时可能是未定义的,但我不知道其他的。

Are any of the functions guaranteed to be available when they are called?是否有任何函数在被调用时保证可用?

It looks like they are all unreliable, except for the onload() invocation.看起来它们都是不可靠的,除了onload()调用。

This page:这一页:

<!DOCTYPE html>
<html>

<head>
    <title>Load script</title>
    <meta charset="UTF-8" />
    <script async="async" src="script.js"></script>
    <script> one() </script>
</head>

<body onload="two()">
    <p>Test</p>
    <script> three() </script>
</body>

<script> four() </script>

</html>

<script> five() </script>

produces:产生:

1、3、4 和 5 的错误消息,2 的日志条目

but everything works fine without the async :但是没有async一切正常:

1、3、4、5 和 2 的日志条目

Ie you can be sure the async script has finished when the onload() happens, but not before that .即你可以确定在onload()发生时异步脚本已经完成,但不是在那之前

So in general, for async script loading:所以一般来说,对于异步脚本加载:

  • Nothing in the HTML can rely on the script's having been loaded. HTML 中的任何内容都不能依赖脚本已加载。
  • Nothing in the script can rely on anything in the HTML having been loaded.脚本中的任何内容都不能依赖已加载的 HTML 中的任何内容。

That severely restricts the circumstances under which async scripts can be used.这严重限制了可以使用异步脚本的情况。

The async scripts must not do anything other than defining functions, etc. And those functions can't be used in the HTML until the processing has reached the onload stage.除了定义函数等,异步脚本不能做任何事情。在处理到达加载阶段之前,这些函数不能在onload中使用。

<tag onclick="external_function()"> ... </tag>       <!-- works -->

<script> something = external_function() </script>   <!-- fails -->

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM