DOMContentLoaded

Timing: DOM loading is complete, but image, CSS external resources may not complete loading

Application: The DOM is ready, so the handler can find the DOM node and initialize the interface.

The DOMContentLoaded event occurs on the Document object.

document.addEventListener("DOMContentLoaded", ready);
Copy the code
<script> function ready() { alert('DOM is ready'); Alert (' Image size: ${img.offsetwidth}x${img.offsetheight} '); alert(' Image size: ${img.offsetheight} '); } document.addEventListener("DOMContentLoaded", ready); </script> <img id="img" src="https://en.js.cx/clipart/train.gif? speed=1&cache=0">Copy the code

Loaded

Timing: The browser has loaded not only the HTML, but also all external resources: images, styles, etc. Apply: External resources are loaded, styles are applied, and image sizes are known.

DOMContentLoaded and scripts

When the browser processes an HTML document and encounters it in the document

Therefore, DOMContentLoaded must occur after execution of the following scripts:

There are two exceptions to this rule:

Scripts with async attributes do not block DOMContentLoaded, as we’ll talk about later. DOMContentLoaded is also not blocked by scripts that are dynamically generated using document.createElement(‘script’) and added to a web page.

DOMContentLoaded and style

External stylesheets do not affect the DOM, so DOMContentLoaded does not wait for them.

But there’s a catch. If there is a script behind the style, the script must wait for the stylesheet to complete loading:

<link type="text/ CSS "rel="stylesheet" href="style.css"> None of the scripts executes alert(getComputedStyle(document.body).margintop); </script>Copy the code

The reason is that the script might want to get the coordinates and other style-related attributes of the element, as shown in the example above. Therefore, it must wait for the style load to complete.

While DOMContentLoaded waits for the script, it is now also waiting for the style in front of the script.

conclusion

Page life cycle events:

  • When the DOM is ready, the DOMContentLoaded event on the Document is fired. At this stage, we can apply JavaScript to the element.

Such as < script >… < / script > or < script SRC = “…” Scripts like > block DOMContentLoaded and the browser waits for them to finish executing. Images and other resources can still be loaded.

  • The load event on the window is triggered when the page and all resources are loaded. We rarely use it because we usually don’t have to wait that long.
  • The beforeUnload event on the Window is fired when the user wants to leave the page. If we cancel this event, the browser will ask if we really want to leave (for example, we have unsaved changes).
  • When the user finally leaves, the Unload event on the Window is fired. In the handler, we can only perform simple operations that do not involve delay or questioning the user. Because of this limitation, it is rarely used. We can use navigator. SendBeacon to send network requests.
    • Document. readyState is the current state of the document and can track state changes in the readyStatechange event:
    • Loading — The document is being loaded.
    • Interactive — The document has been parsed, occurring almost at the same time as DOMContentLoaded but before DOMContentLoaded.
    • Complete — Both the document and the resource are loaded, almost simultaneously with window.onload, but before window.onload.

The script to load

defer

  • Scripts with the defer feature do not block the page.
  • Scripts with the defer feature always wait until DOM parsing is complete, but execute before the DOMContentLoaded event
  • Scripts with the defer feature keep their relative order, just like regular scripts.
  • !!!!!!!!! The defer feature only works with external scripts

async

The Async feature means that scripts are completely independent:

  • The browser will not block due to async scripts (similar to defer).
  • Other scripts do not wait for async scripts to finish loading, and async scripts do not wait for other scripts.
  • DOMContentLoaded and asynchronous scripts don’t wait for each other:
  • DOMContentLoaded may occur before the asynchronous script (if the asynchronous script is loaded after the page is complete)
  • DOMContentLoaded can also occur after an asynchronous script (if the asynchronous script is short or loaded from an HTTP cache)

Asynchronous loading is great when we integrate independent third-party scripts into the page: counters, ads, etc., because they don’t depend on our script, and our script shouldn’t wait for them:

Dynamic script

In addition, there is an important way to add scripts to a page.

We can use JavaScript to dynamically create a script and append it to a document:

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

!!!!!!!!! By default, dynamic scripts behave “asynchronously.”

Module script

<script type="module"></script>

Module scripts are always deferred, in the same way that the defer feature (described in the Scripts: Async, Defer chapter) affects external and inline scripts.

Download external module scripts

Async can be used for inline scripts.

conclusion

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.