最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Window.onload vs script defer - Stack Overflow

programmeradmin4浏览0评论

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

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

Share Improve this question edited Jun 20, 2018 at 21:06 MD Ashik 9,83510 gold badges55 silver badges61 bronze badges asked Dec 4, 2014 at 17:19 user2022068user2022068
Add a comment  | 

1 Answer 1

Reset to default 19

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.

发布评论

评论列表(0)

  1. 暂无评论