Search code examples
javascriptcdn

When do the imports in this JavaScript file served from a CDN occur?


I was just reading an article on Medium (https://medium.com/@mariusbongarts/showcase-your-medium-articles-with-web-components-part-1-basics-d2c6618e9482). As a demonstration of web components, the author provides a CDN link to a JavaScript file along with a custom component.

If I look at the contents of the JavaScript file, I can see that it imports from files which, I assume, exist in the same folder on the same server:

import { getRssFeed } from "./services/medium-feed.js";
import "./components/medium-articles.js";
import "./components/medium-header.js";

My question is - when do these things actually get imported? They must occur before the file reaches me, otherwise they wouldn't be accessible. So does that mean all the code in the file gets run before it's sent to me? Just the imports? Is this something done by the CDN? I'm confused because I thought, when you fetch an asset like a JavaScript file from somewhere else, it's just sent over the network and then it's run once it reaches the browser.


Solution

  • What gets sent to you for that file is exactly what you've shown:

    import { getRssFeed } from "./services/medium-feed.js";
    import "./components/medium-articles.js";
    import "./components/medium-header.js";
    

    Then, the JavaScript engine loads that module and as part of that, it determines that the module depends on other modules, so it fetches those modules (e.g., downloads them) and loads them, building up the module tree in memory.

    This doesn't happen in advance. It happens when you load the module. (That said, often people use module bundlers to combine modules into a single downloadable resource. But if the text of the module is as shown, that's not happening here.)

    More on the process of loading modules in this excellent article by Lin Clark (and, if you're interested, in my book from a couple of years ago JavaScript: The New Toys, Chapter 13).