简体   繁体   English

脚本标签 - 异步和延迟

[英]Script Tag - async & defer

I have a couple of questions about the attributes async & defer for the <script> tag which to my understanding only work in HTML5 browsers.我有几个关于<script>标签的asyncdefer属性的问题,据我所知,这只适用于 HTML5 浏览器。

One of my sites has two external JavaScript files that currently sit just above the </body> tag;我的一个站点有两个外部 JavaScript 文件,它们目前位于</body>标记之上; the first is sourced from google and the second is a local external script.第一个是来自 google 的 ,第二个是本地外部脚本。

With respects to site load speed关于站点加载速度

  1. Is there any advantage in adding async to the two scripts I have at the bottom of the page?async添加到页面底部的两个脚本有什么好处吗?

  2. Would there be any advantage in adding the async option to the two scripts and putting them at the top of the page in the <head> ?async选项添加到两个脚本并将它们放在<head>中的页面顶部会有什么好处吗?

  3. Would this mean they download as the page loads?这是否意味着他们在页面加载时下载?

  4. I assume this would cause delays for HTML4 browsers, but would it speed up page load for HTML5 browsers?我认为这会导致 HTML4 浏览器延迟,但它会加快 HTML5 浏览器的页面加载速度吗?

Using <script defer src=...使用<script defer src=...

  1. Would loading the two scripts inside <head> with the attribute defer the same affect as having the scripts before </body> ?使用属性defer<head>中加载两个脚本是否会产生与在</body>之前加载脚本相同的效果?
  2. Once again I assume this would slow up HTML4 browsers.我再次假设这会减慢 HTML4 浏览器的速度。

Using <script async src=...使用<script async src=...

If I have two scripts with async enabled如果我有两个启用async的脚本

  1. Would they download at the same time?他们会同时下载吗?
  2. Or one at a time with the rest of the page?还是与页面的其余部分一次一个?
  3. Does the order of scripts then become a problem?脚本的顺序会成为问题吗? For example one script depends on the other so if one downloads faster, the second one might not execute correctly etc.例如,一个脚本依赖于另一个脚本,因此如果一个脚本下载速度更快,则第二个脚本可能无法正确执行等。

Finally am I best to leave things as they are until HTML5 is more commonly used?最后,在 HTML5 更常用之前,我最好保持原样吗?

This image explains normal script tag, async and defer这张图片解释了普通的脚本标签、异步和延迟

在此处输入图像描述

  • Async scripts are executed as soon as the script is loaded, so it doesn't guarantee the order of execution (a script you included at the end may execute before the first script file )加载脚本后立即执行异步脚本,因此它不能保证执行顺序(您最后包含的脚本可能在第一个脚本文件之前执行)

  • Defer scripts guarantees the order of execution in which they appear in the page.延迟脚本保证它们出现在页面中的执行顺序。

Ref this link : http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html参考此链接: http ://www.growthwiththeweb.com/2014/02/async-vs-defer-attributes.html

Keep your scripts right before </body> .将您的脚本放在</body>之前。 Async can be used with scripts located there in a few circumstances (see discussion below).在少数情况下,异步可以与位于那里的脚本一起使用(参见下面的讨论)。 Defer won't make much of a difference for scripts located there because the DOM parsing work has pretty much already been done anyway. Defer 不会对位于那里的脚本产生太大影响,因为 DOM 解析工作几乎已经完成。

Here's an article that explains the difference between async and defer: http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/ .这是一篇解释异步和延迟之间区别的文章:http: //peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/

Your HTML will display quicker in older browsers if you keep the scripts at the end of the body right before </body> .如果您将脚本保留在正文末尾的</body>之前,您的 HTML 将在旧浏览器中显示得更快。 So, to preserve the load speed in older browsers, you don't want to put them anywhere else.因此,为了保持旧浏览器的加载速度,您不想将它们放在其他任何地方。

If your second script depends upon the first script (eg your second script uses the jQuery loaded in the first script), then you can't make them async without additional code to control execution order, but you can make them defer because defer scripts will still be executed in order, just not until after the document has been parsed.如果您的第二个脚本依赖于第一个脚本(例如,您的第二个脚本使用第一个脚本中加载的 jQuery),那么您不能在没有额外代码来控制执行顺序的情况下使它们异步,但您可以使它们延迟,因为延迟脚本会仍然按顺序执行,只是在文档被解析之后才执行。 If you have that code and you don't need the scripts to run right away, you can make them async or defer.如果您有该代码并且不需要立即运行脚本,则可以使它们异步或延迟。

You could put the scripts in the <head> tag and set them to defer and the loading of the scripts will be deferred until the DOM has been parsed and that will get fast page display in new browsers that support defer, but it won't help you at all in older browsers and it isn't really any faster than just putting the scripts right before </body> which works in all browsers.您可以将脚本放在<head>标记中并将它们设置为defer并且脚本的加载将被延迟,直到 DOM 被解析,这将在支持 defer 的新浏览器中快速显示页面,但它不会在较旧的浏览器中完全可以帮助您,并且实际上并不比将脚本放在适用于所有浏览器的</body>之前更快。 So, you can see why it's just best to put them right before </body> .因此,您可以了解为什么最好将它们放在</body>之前。

Async is more useful when you really don't care when the script loads and nothing else that is user dependent depends upon that script loading.当您真的不关心脚本何时加载并且没有其他用户依赖于该脚本加载时,异步会更有用。 The most often cited example for using async is an analytics script like Google Analytics that you don't want anything to wait for and it's not urgent to run soon and it stands alone so nothing else depends upon it.使用异步最常被引用的示例是像 Google Analytics 这样的分析脚本,您不想等待任何东西,并且很快运行并不急迫,它是独立的,所以没有其他东西依赖它。

Usually the jQuery library is not a good candidate for async because other scripts depend upon it and you want to install event handlers so your page can start responding to user events and you may need to run some jQuery-based initialization code to establish the initial state of the page.通常 jQuery 库不适合异步,因为其他脚本依赖于它,并且您希望安装事件处理程序以便您的页面可以开始响应用户事件,并且您可能需要运行一些基于 jQuery 的初始化代码来建立初始状态的页面。 It can be used async, but other scripts will have to be coded to not execute until jQuery is loaded.它可以异步使用,但其他脚本必须在加载 jQuery 之前进行编码才能执行。

HTML5: async , defer HTML5: asyncdefer

In HTML5, you can tell browser when to run your JavaScript code.在 HTML5 中,您可以告诉浏览器何时运行您的 JavaScript 代码。 There are 3 possibilities:有3种可能:

<script       src="myscript.js"></script>

<script async src="myscript.js"></script>

<script defer src="myscript.js"></script>
  1. Without async or defer , browser will run your script immediately, before rendering the elements that's below your script tag.如果没有asyncdefer ,浏览器将立即运行您的脚本,然后再渲染您的 script 标签下方的元素。

  2. With async (asynchronous), browser will continue to load the HTML page and render it while the browser load and execute the script at the same time.使用async (异步),浏览器将继续加载 HTML 页面并呈现它,同时浏览器同时加载和执行脚本。

  3. With defer , browser will run your script when the page finished parsing.使用defer ,浏览器将在页面完成解析时运行您的脚本。 (not necessary finishing downloading all image files. This is good.) (不需要完成所有图像文件的下载。这很好。)

Both async and defer scripts begin to download immediately without pausing the parser and both support an optional onload handler to address the common need to perform initialization which depends on the script. asyncdefer脚本都立即开始下载而不暂停解析器,并且都支持可选的onload处理程序来解决执行依赖于脚本的初始化的常见需求。

The difference between async and defer centers around when the script is executed. asyncdefer之间的区别集中在脚本执行的时间上。 Each async script executes at the first opportunity after it is finished downloading and before the window's load event.每个async脚本在完成下载后和窗口的加载事件之前第一次执行。 This means it's possible (and likely) that async scripts are not executed in the order in which they occur in the page.这意味着async脚本有可能(并且很可能)没有按照它们在页面中出现的顺序执行。 Whereas the defer scripts, on the other hand, are guaranteed to be executed in the order they occur in the page.而另一方面, defer脚本保证按照它们在页面中出现的顺序执行。 That execution starts after parsing is completely finished, but before the document's DOMContentLoaded event.该执行在解析完全完成后开始,但在文档的DOMContentLoaded事件之前。

Source & further details: here .来源和更多细节:这里

Faced same kind of problem and now clearly understood how both will works.Hope this reference link will be helpful...面临同样的问题,现在清楚地了解两者将如何工作。希望这个参考链接会有所帮助......

Async异步

When you add the async attribute to your script tag, the following will happen.当您将 async 属性添加到脚本标记时,将发生以下情况。

<script src="myfile1.js" async></script>
<script src="myfile2.js" async></script>
  1. Make parallel requests to fetch the files.发出并行请求以获取文件。
  2. Continue parsing the document as if it was never interrupted.继续解析文档,就好像它从未被中断过一样。
  3. Execute the individual scripts the moment the files are downloaded.下载文件时执行各个脚本。

Defer推迟

Defer is very similar to async with one major differerence. Defer 与 async 非常相似,但有一个主要区别。 Here's what happens when a browser encounters a script with the defer attribute.当浏览器遇到具有 defer 属性的脚本时,会发生以下情况。

<script src="myfile1.js" defer></script>
<script src="myfile2.js" defer></script>
  1. Make parallel requests to fetch the individual files.发出并行请求以获取单个文件。
  2. Continue parsing the document as if it was never interrupted.继续解析文档,就好像它从未被中断过一样。
  3. Finish parsing the document even if the script files have downloaded.即使脚本文件已下载,也完成对文档的解析。
  4. Execute each script in the order they were encountered in the document.按照在文档中遇到的顺序执行每个脚本。

Reference : Difference between Async and Defer参考: 异步和延迟之间的区别

async and defer will download the file during HTML parsing. asyncdefer将在 HTML 解析期间下载文件。 Both will not interrupt the parser.两者都不会中断解析器。

  • The script with async attribute will be executed once it is downloaded.具有async属性的脚本将在下载后执行。 While the script with defer attribute will be executed after completing the DOM parsing.而具有defer属性的脚本将在完成 DOM 解析后执行。

  • The scripts loaded with async doesn't guarantee any order.使用async加载的脚本不保证任何顺序。 While the scripts loaded with defer attribute maintains the order in which they appear on the DOM.使用defer属性加载的脚本会保持它们在 DOM 上出现的顺序。

Use <script async> when the script does not rely on anything.当脚本不依赖任何东西时使用<script async> when the script depends use <script defer> .当脚本依赖时使用<script defer>

Best solution would be add the <script> at the bottom of the body.最好的解决方案是在正文底部添加<script> There will be no issue with blocking or rendering.阻塞或渲染不会有问题。

Good practice is to keep all the files in your source folder to load sorce files fast.好的做法是将所有文件保留在源文件夹中以快速加载源文件。 You need to download all the script, style, icon and image related files and put these files into your project folder.您需要下载所有与脚本、样式、图标和图像相关的文件,并将这些文件放入您的项目文件夹中。

Create these folders in your project to keep different source files and then load required files into the pages from these folder.在您的项目中创建这些文件夹以保存不同的源文件,然后将所需文件从这些文件夹加载到页面中。

js: to keep script related files. js:保存脚本相关文件。

css: to keep style related files. css:保存样式相关文件。

img: to keep image/icon related files img:保存图像/图标相关文件

fonts: to keep fonts related files fonts:保存字体相关文件


When to use defer and async attribute何时使用 defer 和 async 属性

defer attribute: First it will download the script file and then wait of html parsing. defer 属性:首先它会下载脚本文件,然后等待 html 解析。 After the end of html parsing, script will execute. html解析结束后,将执行脚本。 In other words, It will guarantee all the scripts will execute after the html parsing.换句话说,它将保证所有脚本在 html 解析后执行。

Defer attribute is useful when script is using for DOM manipulations.当脚本用于 DOM 操作时,延迟属性很有用。 Means script will apply on document html.意味着脚本将应用于文档 html。

async attribute: It will download the script file and execute without wait the end of html parsing. async 属性:它将下载脚本文件并执行,无需等待 html 解析结束。 In other words, It will not guarantee all the scripts will execute after the html parsing.换句话说,它不能保证所有的脚本都会在 html 解析之后执行。

Async attribute is useful when script is not using for DOM manipulation.当脚本不用于 DOM 操作时,异步属性很有用。 Some time you need script only for server side operations or for handling cache or cookie but not for DOM manipulations.有时您只需要脚本用于服务器端操作或处理缓存或 cookie,而不需要用于 DOM 操作。 Means script is not related to the used html.表示脚本与使用的 html 无关。

在此处输入图像描述


Useful link when to use defer and async: https://stackoverflow.com/a/68929270/7186739何时使用延迟和异步的有用链接: https ://stackoverflow.com/a/68929270/7186739

I think Jake Archibald presented us some insights back in 2013 that might add even more positiveness to the topic:我认为 Jake Archibald 早在 2013 年就向我们展示了一些见解,这些见解可能会为该主题增添更多积极性:

https://www.html5rocks.com/en/tutorials/speed/script-loading/ https://www.html5rocks.com/en/tutorials/speed/script-loading/

The holy grail is having a set of scripts download immediately without blocking rendering and execute as soon as possible in the order they were added.圣杯是在不阻塞渲染的情况下立即下载一组脚本,并按照它们添加的顺序尽快执行。 Unfortunately HTML hates you and won't let you do that.不幸的是,HTML 讨厌你,不会让你那样做。

(...) (...)

The answer is actually in the HTML5 spec, although it's hidden away at the bottom of the script-loading section.答案实际上在 HTML5 规范中,尽管它隐藏在脚本加载部分的底部。 " The async IDL attribute controls whether the element will execute asynchronously or not. If the element's "force-async" flag is set, then, on getting, the async IDL attribute must return true, and on setting, the "force-async" flag must first be unset… ". " async IDL 属性控制元素是否异步执行。如果设置了元素的“force-async”标志,则在获取时,async IDL 属性必须返回 true,而在设置时,“force-async”标志必须首先取消设置…… ”。

(...) (...)

Scripts that are dynamically created and added to the document are async by default , they don't block rendering and execute as soon as they download, meaning they could come out in the wrong order.动态创建并添加到文档中的脚本默认是异步的,它们不会阻止渲染并在下载后立即执行,这意味着它们可能会以错误的顺序出现。 However, we can explicitly mark them as not async:但是,我们可以明确地将它们标记为非异步:

[
    '//other-domain.com/1.js',
    '2.js'
].forEach(function(src) {
    var script = document.createElement('script');
    script.src = src;
    script.async = false;
    document.head.appendChild(script);
});

This gives our scripts a mix of behaviour that can't be achieved with plain HTML.这为我们的脚本提供了使用纯 HTML 无法实现的混合行为。 By being explicitly not async, scripts are added to an execution queue, the same queue they're added to in our first plain-HTML example.通过显式地不异步,脚本被添加到执行队列中,与我们在第一个纯 HTML 示例中添加的队列相同。 However, by being dynamically created, they're executed outside of document parsing, so rendering isn't blocked while they're downloaded (don't confuse not-async script loading with sync XHR, which is never a good thing).但是,通过动态创建,它们在文档解析之外执行,因此在下载它们时不会阻止渲染(不要将非异步脚本加载与同步 XHR 混淆,这绝不是一件好事)。

The script above should be included inline in the head of pages, queueing script downloads as soon as possible without disrupting progressive rendering, and executes as soon as possible in the order you specified.上面的脚本应该包含在页面头部内联,在不中断渐进式渲染的情况下尽快排队下载脚本,并按照您指定的顺序尽快执行。 “2.js” is free to download before “1.js”, but it won't be executed until “1.js” has either successfully downloaded and executed, or fails to do either. “2.js”在“1.js”之前可以免费下载,但要等到“1.js”下载并执行成功或失败后才会执行。 Hurrah!欢呼! async-download but ordered-execution !异步下载但有序执行

Still, this might not be the fastest way to load scripts:不过,这可能不是加载脚本的最快方式:

(...) With the example above the browser has to parse and execute script to discover which scripts to download. (...) 对于上面的示例,浏览器必须解析和执行脚本以发现要下载的脚本。 This hides your scripts from preload scanners.这会从预加载扫描器中隐藏您的脚本。 Browsers use these scanners to discover resources on pages you're likely to visit next, or discover page resources while the parser is blocked by another resource.浏览器使用这些扫描器来发现您接下来可能访问的页面上的资源,或者在解析器被另一个资源阻止时发现页面资源。

We can add discoverability back in by putting this in the head of the document:我们可以通过将其放在文档的头部来添加可发现性:

<link rel="subresource" href="//other-domain.com/1.js">
<link rel="subresource" href="2.js">

This tells the browser the page needs 1.js and 2.js.这告诉浏览器页面需要 1.js 和 2.js。 link[rel=subresource] is similar to link[rel=prefetch], but with different semantics. link[rel=subresource] 类似于 link[rel=prefetch],但语义不同。 Unfortunately it's currently only supported in Chrome, and you have to declare which scripts to load twice, once via link elements, and again in your script.不幸的是,它目前仅在 Chrome 中受支持,您必须声明两次加载哪些脚本,一次通过链接元素,然后再次在您的脚本中。

Correction: I originally stated these were picked up by the preload scanner, they're not, they're picked up by the regular parser.更正:我最初说这些是由预加载扫描器拾取的,它们不是,它们是由常规解析器拾取的。 However, preload scanner could pick these up, it just doesn't yet, whereas scripts included by executable code can never be preloaded.但是,预加载扫描程序可以选择这些,但它还没有,而可执行代码中包含的脚本永远不能被预加载。 Thanks to Yoav Weiss who corrected me in the comments.感谢 Yoav Weiss 在评论中纠正了我。

It seems the behavior of defer and async is browser dependent, at least on the execution phase.似乎 defer 和 async 的行为取决于浏览器,至少在执行阶段是这样。 NOTE, defer only applies to external scripts.注意, defer 仅适用于外部脚本。 I'm assuming async follows same pattern.我假设 async 遵循相同的模式。

In IE 11 and below, the order seems to be like this:在 IE 11 及更低版本中,顺序似乎是这样的:

  • async (could partially execute while page loading)异步(在页面加载时可以部分执行)
  • none (could execute while page loading)无(可以在页面加载时执行)
  • defer (executes after page loaded, all defer in order of placement in file) defer(在页面加载后执行,所有延迟按文件中的放置顺序)

In Edge, Webkit, etc, the async attribute seems to be either ignored or placed at the end:在 Edge、Webkit 等中,async 属性似乎被忽略或放在最后:

  • data-pagespeed-no-defer (executes before any other scripts, while page is loading) data-pagespeed-no-defer(在任何其他脚本之前执行,同时页面正在加载)
  • none (could execute while page is loading)无(可以在页面加载时执行)
  • defer (waits until DOM loaded, all defer in order of placement in file) defer (等到 DOM 加载完毕,全部按文件中的放置顺序延迟)
  • async (seems to wait until DOM loaded)异步(似乎要等到 DOM 加载)

In newer browsers, the data-pagespeed-no-defer attribute runs before any other external scripts.在较新的浏览器中, data-pagespeed-no-defer 属性在任何其他外部脚本之前运行。 This is for scripts that don't depend on the DOM.这适用于不依赖于 DOM 的脚本。

NOTE: Use defer when you need an explicit order of execution of your external scripts.注意:当您需要明确的外部脚本执行顺序时,请使用 defer。 This tells the browser to execute all deferred scripts in order of placement in the file.这告诉浏览器按文件中的放置顺序执行所有延迟脚本。

ASIDE: The size of the external javascripts did matter when loading...but had no effect on the order of execution.旁白:加载时外部 javascript 的大小确实很重要……但对执行顺序没有影响。

If you're worried about the performance of your scripts, you may want to consider minification or simply loading them dynamically with an XMLHttpRequest.如果您担心脚本的性能,您可能需要考虑缩小或简单地使用 XMLHttpRequest 动态加载它们。

Rendering engine goes several steps till it paints anything on the screen.渲染引擎经过几个步骤,直到它在屏幕上绘制任何内容。

it looks like this:它看起来像这样:

  1. Converting HTML bytes to characters depending on encoding we set to the document;根据我们为文档设置的编码将 HTML 字节转换为字符;
  2. Tokens are created according to characters.令牌是根据字符创建的。 Tokens mean analyze characters and specify opening tangs and nested tags;标记意味着分析字符并指定开头的唐和嵌套的标签;
  3. From tokens separated nodes are created.从令牌中创建分离的节点。 they are objects and according to information delivered from tokenization process, engine creates objects which includes all necessary information about each node;它们是对象,根据标记化过程传递的信息,引擎创建对象,其中包括有关每个节点的所有必要信息;
  4. after that DOM is created.在创建 DOM 之后。 DOM is tree data structure and represents whole hierarchy and information about relationship and specification of tags; DOM 是树形数据结构,表示整个层次结构以及关于标签关系和规范的信息;

The same process goes to CSS.同样的过程也适用于 CSS。 for CSS rendering engine creates different/separated data structure for CSS but it's called CSSOM (CSS Object Model) CSS渲染引擎为CSS创建不同/分离的数据结构,但它被称为CSSOM(CSS对象模型)

Browser works only with Object models so it needs to know all information about DOM and CSSDOM.浏览器仅适用于对象模型,因此它需要了解有关 DOM 和 CSSDOM 的所有信息。

The next step is combining somehow DOM and CSSOM.下一步是以某种方式结合 DOM 和 CSSOM。 because without CSSOM browser do not know how to style each element during rendering process.因为没有 CSSOM 的浏览器不知道如何在渲染过程中设置每个元素的样式。

All information above means that, anything you provide in your html (javascript, css ) browser will pause DOM construction process.以上所有信息意味着,您在 html(javascript、css)浏览器中提供的任何内容都会暂停 DOM 构建过程。 If you are familiar with event loop, there is simple rule how event loop executes tasks:如果您熟悉事件循环,那么事件循环如何执行任务有一个简单的规则:

  1. Execute macro tasks;执行宏任务;
  2. execute micro tasks;执行微任务;
  3. Rendering;渲染;

So when you provide Javascript file, browser do not know what JS code is going to do and stops all DOM construction process and Javascript interptreter starts parsing and executing Javascript code.因此,当您提供 Javascript 文件时,浏览器不知道 JS 代码要做什么,并停止所有 DOM 构建过程,Javascript 解释器开始解析和执行 Javascript 代码。

Even you provide Javascript in the end of body tag, Browser will proceed all above steps to HTML and CSS but except rendering.即使您在 body 标记的末尾提供 Javascript,浏览器也会对 HTML 和 CSS 执行上述所有步骤,但渲染除外。 it will find out Script tag and will stop until JS is done.它会找出 Script 标签并停止,直到 JS 完成。

But HTML provided two additional options for script tag: async and defer.但是 HTML 为 script 标签提供了两个额外的选项:async 和 defer。

Async - means execute code when it is downloaded and do not block DOM construction during downloading process.异步 - 表示下载时执行代码,并且在下载过程中不阻塞 DOM 构建。

Defer - means execute code after it's downloaded and browser finished DOM construction and rendering process. Defer - 表示在代码下载完成并且浏览器完成 DOM 构建和渲染过程后执行代码。

正常 vs 异步 vs 延迟

Normal vs Async vs Defer in a nut shell简而言之,普通 vs 异步 vs 延迟

  1. Default - By default, as soon as the browser sees a script tag it downloads the file and then executes the script file.默认- 默认情况下,一旦浏览器看到脚本标签,它就会下载文件,然后执行脚本文件。 The script files are executed in the order of their occurrence.脚本文件按它们出现的顺序执行。

  2. async - The browser will download the script file and continue parsing HTML parallelly until the file is downloaded. async - 浏览器将下载脚本文件并继续并行解析 HTML,直到文件下载完毕。 The file is executed as soon as it is downloaded.下载文件后立即执行。

  3. defer - The browser will download the script and do HTML parsing at the same time. defer - 浏览器将下载脚本并同时进行 HTML 解析。 After parsing is done, the script files are executed in the order of their occurrence.解析完成后,脚本文件按照它们出现的顺序执行。

Note: In defer, the js files are executed in the order of their occurrence in the HTML file while in the case of the async attribute the script files are executed in the order of download time.注意:在 defer 中,js 文件按照它们在 HTML 文件中出现的顺序执行,而在 async 属性的情况下,脚本文件按照下载时间的顺序执行。

Async is suitable if your script doesn't contains DOM manipulation and other scripts doesn't depend upon on this.如果您的脚本不包含 DOM 操作并且其他脚本不依赖于此,则异步是合适的。 Eg: bootstrap cdn,jquery例如:引导 cdn、jquery

Defer is suitable if your script contains DOM manipulation and other scripts depend upon on this.如果您的脚本包含 DOM 操作并且其他脚本依赖于此,则延迟适用。

Eg: <script src=”createfirst.js”> //let this will create element <script src=”showfirst.js”> //after createfirst create element it will show that.例如: <script src=”createfirst.js”> //let this will create element <script src=”showfirst.js”> //after createfirst create element it will show that.

Thus make it: Eg: <script defer src=”createfirst.js”> //let this will create element <script defer src=”showfirst.js”> //after createfirst create element it will从而使它: 例如: <script defer src=”createfirst.js”> //let this will create element <script defer src=”showfirst.js”> //after createfirst create element it will

This will execute scripts in order.这将按顺序执行脚本。

But if i made: Eg: <script async src=”createfirst.js”> //let this will create element <script defer src=”showfirst.js”> //after createfirst create element it will但是如果我做了:例如: <script async src=”createfirst.js”> //let this will create element <script defer src=”showfirst.js”> //after createfirst create element it will

Then, this code might result unexpected results.然后,此代码可能会导致意外结果。 Coz: if html parser access createfirst script.It won't stop DOM creation and starts downloading code from src .Once src got resolved/code got downloaded, it will execute immediately parallel with DOM. Coz:如果 html 解析器访问 createfirst 脚本。它不会停止 DOM 创建并开始从 src 下载代码。一旦 src 被解析/代码被下载,它将立即与 DOM 并行执行。

What if showfirst.js execute first than createfirst.js.This might be possible if createfirst takes long time (Assume after DOM parsing finished).Then, showfirst will execute immediately.如果 showfirst.js 比 createfirst.js 先执行怎么办。如果 createfirst 需要很长时间(假设在 DOM 解析完成后),这可能是可能的。然后,showfirst 将立即执行。

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

相关问题 下一个 JS 脚本组件与具有异步和延迟的普通脚本标签 - Next JS Script Component Vs normal script tag with async and defer 如何正确使用脚本标记中的延迟/异步属性 - How to use defer/async attributes in script tag properly 3rd 方脚本标签中异步与延迟的性能影响 - Performance impact of async vs defer in 3rd party script tag 如何以及在哪里导入和放置脚本标签? 异步与延迟 - how and where to import and place script tag ? async vs defer 您可以在 HTML 脚本标签上同时使用 async 和 defer 属性吗? - Can you use both the async and defer attributes on a HTML script tag? HTML 中脚本标记中的 async 和 defer 属性是否与 SPA 应用程序无关? - Are async and defer attributes in script tag in HTML irrelevant for SPA apps? 为什么要通过 Javascript 创建脚本标签,而不是使用延迟或异步脚本标签属性? - Why create script tag via Javascript, instead of using defer or async script tag attributes? 带有异步和/或延迟的脚本上的“加载”事件 - "Load" event on script with async and/or defer 为什么Javascript代码在script标签中设置async或defer时无法执行? - Why Javascript codes cannot be executed when async or defer are set in script tag? 如何在jade中添加脚本标记的属性,例如异步延迟 - how do you add attributes to script tag in jade e.g. async defer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM