Window.onload vs脚本延迟 [英] Window.onload vs script defer
问题描述
未初始化 - 尚未开始加载
加载 - 正在加载
interactive - 已加载并且用户可以与之交互
完成 - 完全加载
这里据说基本上,延迟会告诉浏览器在执行脚本块中的JavaScript之前等待准备就绪。通常这是在DOM完成加载和document.readyState == 4之后的。
所以这个问题首先执行什么以及为什么 - < script defer src =。 ..>或window.onload = function(){...}?
阅读http://www.w3.org/html/wg/drafts/html/master/脚本1.html#attr脚本推迟:
使用这些$可以选择三种可能的模式b $ b属性。如果存在
async
属性,那么该脚本将在
可用时立即执行。 如果async
属性不存在,但存在defer
属性,则
脚本在页面完成解析时执行。如果
属性都不存在,则在用户代理继续解析页面之前立即获取脚本并执行
。 / p>
http://www.w3.org/TR/html5/syntax.html#the-end 告诉你,延迟脚本首先运行:
...
执行脚本列表中的第一个脚本,该脚本将在文档完成解析后执行。
...
blockquote>
然后是
DOMContentLoaded
事件:
load
/ code>事件在两者之后触发总是这样。
Here it's said, that there are 4 readyState possible values for html documents:
uninitialized - Has not started loading yet
loading - Is loading
interactive - Has loaded enough and the user can interact with it
complete - Fully loadedHere it's said that basically, defer tells the browser to wait "until it's ready" before executing the javascript in that script block. Usually this is after the DOM has finished loading and document.readyState == 4
So the question what is executed first and why - the <script defer src="..."> or window.onload=function(){...} ?
解决方案Read on to http://www.w3.org/html/wg/drafts/html/master/scripting-1.html#attr-script-defer:
There are three possible modes that can be selected using these attributes. If the
async
attribute is present, then the script will be executed asynchronously, as soon as it is available. If theasync
attribute is not present but thedefer
attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.http://www.w3.org/TR/html5/syntax.html#the-end tells you that deferred scripts run first:
…
Execute the first script in the list of scripts that will execute when the document has finished parsing.
…Then the
DOMContentLoaded
event:Queue a task to fire a simple event that bubbles named DOMContentLoaded at the Document.
load
events fire after both of these, always.这篇关于Window.onload vs脚本延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!