脚本标记 - 异步和延迟

本文翻译自:Script Tag - async & defer

I have a couple of questions about the attributes async & defer for the

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

  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.) (没必要完成下载所有图像文件。这很好。)


#4楼

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 . 来源及进一步细节: 这里 。


#5楼

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 does n'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

你可能感兴趣的:(脚本标记 - 异步和延迟)