Page life cycle

[1] initial readyState:loading [2] readyState:interactive [2] DOMContentLoaded [3] iframe onload [4] img onload [4] readyState:complete [4] window onload

The numbers in square brackets indicate the approximate time that this happened. Events marked with the same number occur almost simultaneously (± milliseconds).

  • inDOMContentLoadedBefore,document.readyStateWill immediately becomeinteractive. They’re actually the same thing.
  • When all resources (iframeimg) after everything is loaded,document.readyStatebecomecomplete. Here we can see that it has a lot to do withimg.onload(imgIs the last resource) andwindow.onloadAlmost at the same time. The switch tocompleteThe meaning of state andwindow.onloadThe same. The difference is thatwindow.onloadAlways at all othersloadThe handler is then run.

Script: async, defer

defer

  • withdeferFeature scripts do not block pages.
  • withdeferFeature scripts always wait until DOM parsing is complete, but beforeDOMContentLoadedEvent before execution.

The browser scans the page for scripts and then downloads them in parallel to improve performance. Therefore, in the example above, the two scripts are downloaded in parallel. Small.js will probably be downloaded first.

… However, in addition to telling the browser “don’t block the page,” the defer feature ensures the relative order of script execution. Therefore, even if small.js is loaded first, it will not be executed until long.js is executed.

async

An async script is a completely separate script that is executed when the load is complete

Dynamic script

let script = document.createElement('script');
script.src = "/article/script-async-defer/long.js";
document.body.append(script); / / (*)
Copy the code

When the script is attached to the document (*), the script starts loading immediately.

By default, dynamic scripts behave “asynchronously.”

  • They don’t wait for anything, and nothing will wait for them.
  • Scripts that are loaded first are executed first (load first order).

We can change this rule if we explicitly set script.async=false. The script will then execute in the order that the scripts are in the document, just as deferred did.

The order DOMContentLoaded
async Load priority. The order of the scripts in the document doesn’t matter — those that are loaded first are executed first Not related. The document may be loaded and executed before it is. This can happen if the script is small or from the cache and the document is long enough.
defer Document order(Their order in the document) After the document has been loaded and parsed (or waited if needed), that isDOMContentLoadedBefore execution.

In real development, defer is used for scripts that require the entire DOM, and/or when the relative execution order of the scripts is important.

Async is used for stand-alone scripts, such as counters or ads, where the relative order of execution is irrelevant.