Here is what I understand based upon MDN Modules and defer:
- All JavaScript modules defer automatically.
- Deferring a module prevents the
DOMContentLoadedevent from firing until the module finishes. - Using an inline
<script type="module">makes the script a module and defers it automatically.
Thus I would expect DOMContentLoaded not to be called until a <script type="module"> is finished. But I tried this code:
<!DOCTYPE html>
<html>
<head>
…
<script type="module">
document.addEventListener("DOMContentLoaded", function () {
console.log("DOMContentLoaded fired");
});
const fooBar = await fetch("foo.bar");
console.log("finished loading data");
document.addEventListener("DOMContentLoaded", function () {
console.log("starting to process data");
//try to process fooBar
});
}
…
Here I would expect the entire script to run, awaiting for the fetching of "foo.bar" and assigning fooBar before DOMContentLoaded is fired. Yet in the console I see:
DOMContentLoaded fired
finished loading data
I never see "starting to process data". It seems that DOMContentLoaded is being fired before the module finishes.
There must be part of the documentation I misinterpreted. How is DOMContentLoaded being called before the completion of a module?