Window.onload vs script defer

隐身守侯 提交于 2019-12-20 19:41:36

问题


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 loaded

Here 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(){...} ?


回答1:


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 the async attribute is not present but the defer 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.



来源:https://stackoverflow.com/questions/27300058/window-onload-vs-script-defer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!