completefrontend

Predict the outputMedium

When does the dynamically imported module run?

The tea shop's page has an inline module script in its head that imports teas.js, and an inline classic script at the end of its body. The module wires the Show the menu button to load menu.js with await import(), and then to import it a second time; menu.js imports teas.js too. Each script and module logs when it runs, with document.readyState, and the page logs DOMContentLoaded and, at load, the files it has fetched so far. You open the page, and once it has loaded you click the button. What does the console show, in order, and when does Chrome fetch menu.js?

index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Leaf and Kettle</title>
  <script type="module">
    import { teas } from "./teas.js";
    console.log("inline module ran, readyState " + document.readyState + ", " + teas.length + " teas");
 
    document.querySelector("#menu").addEventListener("click", async () => {
      console.log("click: asking for menu.js, readyState " + document.readyState);
      const menu = await import("./menu.js");
      console.log("click: menu.js gave " + menu.items.length + " items");
      const again = await import("./menu.js");
      console.log("second import, same module: " + (again === menu));
    });
 
    addEventListener("load", () => {
      const fetched = performance.getEntriesByType("resource").map((entry) => entry.name.split("/").pop());
      console.log("load fired, fetched so far: " + fetched.join(", "));
    });
  </script>
</head>
<body>
  <h1>Leaf and Kettle</h1>
  <button id="menu" type="button">Show the menu</button>
  <script>
    console.log("inline classic script ran, readyState " + document.readyState);
    document.addEventListener("DOMContentLoaded", () => console.log("DOMContentLoaded fired, readyState " + document.readyState));
  </script>
</body>
</html>
teas.js
console.log("teas.js ran, readyState " + document.readyState);
 
export const teas = ["green", "mint", "oolong"];
menu.js
import { teas } from "./teas.js";
 
console.log("menu.js ran, readyState " + document.readyState);
 
export const items = teas.map((tea) => tea + " tea");

Chrome loads these files from a server on the same computer, index.html at /, in a fresh profile with an empty cache, on a phone's screen (412 by 823 CSS pixels), with no network or CPU slowdown.

  1. You open the page in Chrome.
  2. When the page has loaded, you click Show the menu once.

The answer

Work out what Chrome does with the page: every line it logs, in order, and how it treats each file. Then check.

Checking your sign-in…