How JS Modules work: a Browser Perspective

Rate this content
Bookmark

Modules are a popular tool for JavaScript Developers. Recently, there have been a number of proposals touching on how Modules work, including Import Maps, Top level await, JSON modules, Module asserts, and many others. But how does the module loading system work, and how do these proposals augment it? What does it look like from the browsers perspective to load a module tree with an import map? We will explore these questions and more, giving you a behind the scenes look at module loading in JS.

FAQ

SpiderMonkey is the JavaScript compiler used by Mozilla for its Firefox browser. It handles not only JavaScript but also WebAssembly, focusing primarily on compiling JavaScript code efficiently for execution.

The name 'SpiderMonkey' originated from Brendan Eich, the creator of JavaScript. He named it after considering it as the 'ugliest piece of code' he had seen, reminiscent of the ugliest animal he had seen at the zoo, a spider monkey.

CommonJS modules handle loading, parsing, and evaluating synchronously and are primarily used in server environments. ES6 modules, introduced for the web, use asynchronous loading to avoid blocking the main thread, parsing the entire file first before building a module record, crucial for the web's non-blocking nature.

The browser manages cyclic dependencies using a module map that tracks the state of each module. When a cycle is detected, the module map ensures that each module in the cycle can proceed to link and execute without infinite looping, maintaining efficient module resolution.

The module map in JavaScript is used to track the state of each module during the loading process, helping to manage dependencies and handle cyclic relationships between modules efficiently. It ensures that modules are loaded, linked, and executed correctly in the browser.

The ES6 module loading process involves parsing the module code first, then building a module record which outlines the imports and exports. The browser then fetches any necessary scripts based on these records, without evaluating them until the entire graph is ready to be executed.

Yulia Startsev
Yulia Startsev
26 min
16 Jun, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This Talk discusses JavaScript modules from the perspective of a browser, exploring how they work and their differences from common JS. It covers topics such as loading modules, module records, and the module map. The module loading and evaluation process is explained, along with the challenges of module adoption and performance. The Talk also touches on lazy loading, dynamic import, and import reflection. The speaker shares a humorous anecdote during the Q&A session about stealing a shirt from the DOM team.

1. Introduction to JavaScript Modules

Short description:

We're going to talk about JavaScript modules, specifically from the perspective of a browser. I'm Yulia Starzev, a staff software engineer at Mozilla, working on SpiderMonkey. I came across an interesting tweet from my former colleague, Jason Orndorff, about an invariant of programming languages. Let's use the fish as our theme and share a joke from David Foster Wallace about two fish in the ocean.

That is a very cool intro. Incidentally, if anybody is thinking, oh, what question should I ask in the Q&A, ask me about how we got the name SpiderMonkey. It's a funny story.

So hi, everyone. We're going to talk about JavaScript modules. In particular, we're going to take a slightly unusual perspective, which is that of a browser. So my name is, that was fast. My name is Yulia Starzev. I'm a staff software engineer at Mozilla. In particular, I work on SpiderMonkey, which is the JavaScript compiler for Firefox. In fact, it's not just JavaScript, we also do WebAssembly. The portion that I work on is the JavaScript side. I also do a bit of work on the DOM. And my focus is the design and implementation of JavaScript features.

To start this talk, when I was writing it, I was a little stuck and I was like, I don't know how I'm going to tie all of this together and make it entertaining. This is kind of dry stuff. And I came across this great tweet from my former colleague, Jason Orndorff. He used to work on SpiderMonkey with me and I learned a lot from him. Especially about language design and languages. He wrote this great... Let's call it an invariant of all programming languages that implement a string reverse method. Incidentally, JavaScript does not implement string reverse method. But effectively, string.reverse in any language you try it on will not reverse a picture of a fish.

Here we have an example of such a Ruby program in which we have two versions of a fish picture, one done with angle brackets and the other done as an emoji. And you will notice that when we run this code, indeed, the fish remains looking in the same direction. We may say that this fish is invariant, an important word that we'll be using. So fish is our theme, and since I have fish as a theme, I get to use one of my favourite opening jokes from a keynote which comes from David Foster Wallace in his 2005 keynote to a university, which goes something like this. Two fish are swimming along in the ocean and just minding their own business. They're young. They're new to this beautiful blue world, and an older fish comes by and swims along and says, how's the water, boys? It's just a greeting, and this older fish swims off.

2. Introduction to JavaScript Modules (continued)

Short description:

The module system is similar to something we take for granted. ES6 modules were introduced in 2015. Let's explore how modules work, their differences from common JS, and how the module system builds a graph. The module record acts as a blueprint for our module.

A little while later, the two fish are still swimming along in silence when one fish turns to the other and says, what the hell is water? This is a great joke for setting the stage for something that we might take for granted, for something that exists in the ether and seems like just there, something that you don't need to question.

That's a little bit like what the module system is. I imagine that in the last seven years of ES6 modules existing, many of you have adopted it and use it as your primary way of writing JavaScript modules, especially import-export syntax. Oh, yeah, I forgot to fix that! For some reason I have that twice! How did we get here?

One question you might ask is, well, modules, when did they start? How old is this problem? I have some of an answer here for you. I can't give you a definitive answer, but here's a code base that is a piece of code in the Mozilla code base. It's called the MOZ.js component loader. I want to call out the date here, which is 1999. This code base has a special place in my heart because I happen to be working on it today. It's not every day that you get to say that the code that you're writing is ready to go and get its master's degree.

For many of you in the audience, it's likely that modules really came to the forefront with the introduction of node. In particular, this blog post from 2009 by Kevin Dengar is an important touch point, because here he's asking, he's also a former Mozilla employee, he's asking, what server side JavaScript needs? In this blog post, he introduces the need for a module system, and introduces a new community group called the server JS community group. This group was later renamed to common JS, which I imagine sounds rather familiar. As mentioned, six years later, in 2015, ES6 modules were finally introduced into the specification. Browsers took a little longer to implement it. They came in 2018. It introduced a number of features to the browser, including the import-export syntax that many of you are familiar with.

Let's get into the meat of this talk. How do modules work? What is this module system? What does it do? How does it differ from common JS? Why didn't we specify common JS? Eventually, we will get into what the feature looks like for the module system in browsers. One thing to start with is the module system builds a graph. This graph allows cycles. If you have a module importing some neighbour, and that neighbour imports an ancestor of your initial module, this will work. It's an important feature for developer ergonomics. You don't want to always be breaking cycles manually. The browser does this for you. So, how do we actually build this graph? How does it work? How do we ensure that you actually can write your modules in this cyclic manner? I'm going to start from taking the perspective of a node. The node, in this case, in this graph, is going to be a single module script. In the specification, we have a data structure called the module record, and the module record is this node. It's a bit like a blueprint for our fish, for our module that we're writing. And it comes somewhere in the middle of the process that we're about to describe. If you want to take a look at the codebase, I do have the source text for the Mozilla implementation of this linked there.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
Do you have a large product built by many teams? Are you struggling to release often? Did your frontend turn into a massive unmaintainable monolith? If, like me, you’ve answered yes to any of those questions, this talk is for you! I’ll show you exactly how you can build a micro frontend architecture with Remix to solve those challenges.
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
Remix is a web framework that gives you the simple mental model of a Multi-Page App (MPA) but the power and capabilities of a Single-Page App (SPA). One of the big challenges of SPAs is network management resulting in a great deal of indirection and buggy code. This is especially noticeable in application state which Remix completely eliminates, but it's also an issue in individual components that communicate with a single-purpose backend endpoint (like a combobox search for example).
In this talk, Kent will demonstrate how Remix enables you to build complex UI components that are connected to a backend in the simplest and most powerful way you've ever seen. Leaving you time to chill with your family or whatever else you do for fun.
Making JavaScript on WebAssembly Fast
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
JavaScript in the browser runs many times faster than it did two decades ago. And that happened because the browser vendors spent that time working on intensive performance optimizations in their JavaScript engines.Because of this optimization work, JavaScript is now running in many places besides the browser. But there are still some environments where the JS engines can’t apply those optimizations in the right way to make things fast.We’re working to solve this, beginning a whole new wave of JavaScript optimization work. We’re improving JavaScript performance for entirely different environments, where different rules apply. And this is possible because of WebAssembly. In this talk, I'll explain how this all works and what's coming next.
Debugging JS
React Summit 2023React Summit 2023
24 min
Debugging JS
Top Content
As developers, we spend much of our time debugging apps - often code we didn't even write. Sadly, few developers have ever been taught how to approach debugging - it's something most of us learn through painful experience.  The good news is you _can_ learn how to debug effectively, and there's several key techniques and tools you can use for debugging JS and React apps.
Webpack in 5 Years?
JSNation 2022JSNation 2022
26 min
Webpack in 5 Years?
Top Content
What can we learn from the last 10 years for the next 5 years? Is there a future for Webpack? What do we need to do now?
Towards a Standard Library for JavaScript Runtimes
Node Congress 2022Node Congress 2022
34 min
Towards a Standard Library for JavaScript Runtimes
Top Content
You can check the slides for James' talk here.

Workshops on related topic

Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Top Content
WorkshopFree
Hussien Khayoon
Kahvi Patel
2 authors
Using a library might seem easy at first glance, but how do you choose the right library? How do you upgrade an existing one? And how do you wade through the documentation to find what you want?
In this workshop, we’ll discuss all these finer points while going through a general example of building a code editor using CodeMirror in React. All while sharing some of the nuances our team learned about using this library and some problems we encountered.
Testing Web Applications Using Cypress
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
WorkshopFree
Gleb Bahmutov
Gleb Bahmutov
This workshop will teach you the basics of writing useful end-to-end tests using Cypress Test Runner.
We will cover writing tests, covering every application feature, structuring tests, intercepting network requests, and setting up the backend data.
Anyone who knows JavaScript programming language and has NPM installed would be able to follow along.
Build a powerful DataGrid in few hours with Ag Grid
React Summit US 2023React Summit US 2023
96 min
Build a powerful DataGrid in few hours with Ag Grid
WorkshopFree
Mike Ryan
Mike Ryan
Does your React app need to efficiently display lots (and lots) of data in a grid? Do your users want to be able to search, sort, filter, and edit data? AG Grid is the best JavaScript grid in the world and is packed with features, highly performant, and extensible. In this workshop, you’ll learn how to get started with AG Grid, how we can enable sorting and filtering of data in the grid, cell rendering, and more. You will walk away from this free 3-hour workshop equipped with the knowledge for implementing AG Grid into your React application.
We all know that rolling our own grid solution is not easy, and let's be honest, is not something that we should be working on. We are focused on building a product and driving forward innovation. In this workshop, you'll see just how easy it is to get started with AG Grid.
Prerequisites: Basic React and JavaScript
Workshop level: Beginner
0 to Auth in an Hour Using NodeJS SDK
Node Congress 2023Node Congress 2023
63 min
0 to Auth in an Hour Using NodeJS SDK
WorkshopFree
Asaf Shen
Asaf Shen
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.
We will enhance a full-stack JS application (Node.JS backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session for subsequent client requests, validating / refreshing sessions
At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.
Table of contents- A quick intro to core authentication concepts- Coding- Why passwordless matters
Prerequisites- IDE for your choice- Node 18 or higher
Build a Powerful Datagrid With AG Grid
React Summit 2024React Summit 2024
168 min
Build a Powerful Datagrid With AG Grid
WorkshopFree
Brian Love
Brian Love
Does your React app need to efficiently display lots (and lots) of data in a grid? Do your users want to be able to search, sort, filter, and edit data? AG Grid is the best JavaScript grid in the world and is packed with features, highly performant, and extensible. In this workshop, you’ll learn how to get started with AG Grid, how we can enable sorting and filtering of data in the grid, cell rendering, and more. You will walk away from this free 3-hour workshop equipped with the knowledge for implementing AG Grid into your React application.
JavaScript-based full-text search with Orama everywhere
Node Congress 2023Node Congress 2023
49 min
JavaScript-based full-text search with Orama everywhere
Workshop
Michele Riva
Michele Riva
In this workshop, we will see how to adopt Orama, a powerful full-text search engine written entirely in JavaScript, to make search available wherever JavaScript runs. We will learn when, how, and why deploying it on a serverless function could be a great idea, and when it would be better to keep it directly on the browser. Forget APIs, complex configurations, etc: Orama will make it easy to integrate search on projects of any scale.