Window.onload vs script postpone

It says here that there are 4 ready states for html documents:

uninitialized - not yet started loading
upload - upload / download interactive - Loaded enough and the user can interact with it
full - fully loaded

It says here that basically deferral tells the browser to wait "until it's ready" before executing javascript in this script block. This is usually after the completion of the DOM loading and document.readyState == 4

So, the question is what is executed first and why - <script defer src = "..."> or window.onload = function () {...}?

+6
source share
1 answer

Read on 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 absent, but the defer attribute defer present, then the script is executed when the page has finished parsing. If no attribute is present, then the script is retrieved and executed immediately before the user agent continues parsing the page.

http://www.w3.org/TR/html5/syntax.html#the-end reports that pending scripts are executed first:

...
Run the first script in the list of scripts that will be executed when the processing of the document is completed.
...

Then the DOMContentLoaded event:

The queue to trigger a simple event that bubbles with the name DOMContentLoaded in the document.

load fire events after both of them always.

+11
source

Source: https://habr.com/ru/post/979126/


All Articles