Skip to main content

Frontend development · Intermediate · 22 min

Load ES modules in the browser without a bundler using import maps

By Padding · Updated 18 Nov 2026
Modern browsers · HTML Living Standard module scripts and import maps · checked in Chromium with Node.js 26.13

You will build a small Markdown notes page from native browser modules, served over HTTP, with an import map for a vendored library, modulepreload hints and a preview that only downloads when someone asks for it.

On this page

Browsers have run JavaScript modules natively for years. A <script type="module"> can import other files, and the browser fetches them itself, with no bundler, no build step and no node_modules folder on the server. For a small site, a prototype or an internal tool, that can be all you need. The catches are practical: modules must be served over HTTP, import 'some-package' does not work until you tell the browser where that package lives, and every import is a network request that can only start once the file importing it has arrived.

In this tutorial you build a small notes page. It counts the words in a text box and shows a Markdown preview, using the marked library. Along the way you see what type="module" changes, why opening the file from disk fails, how an import map lets you write import { marked } from 'marked', how modulepreload removes a chain of slow requests, and how import() keeps the preview code off the network until someone clicks the button. The last steps check the page with a short Playwright script and help you decide when this setup is enough and when to move to Vite.

If modules in Node are new to you, read use JavaScript modules with import and export first. This tutorial is about what changes when the browser does the loading.

Step 1 · Write a page that loads a module

Make a demo folder with three files: the page, an entry module, and a second module it imports.

Bash
mkdir -p ~/modules-demo
cd ~/modules-demo

cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Notes</title>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Notes</h1>
    <p id="status">Modules have not run.</p>
    <label for="notes">Your notes (Markdown)</label><br>
    <textarea id="notes" rows="8" cols="40">## Meeting notes

- Agree the **launch date**
- Translate the page into French and Hausa</textarea>
    <p id="count" aria-live="polite"></p>
  </main>
</body>
</html>
HTML

cat > format.js <<'JS'
const words = new Intl.Segmenter(undefined, { granularity: 'word' });

export function countWords(text) {
  let total = 0;
  for (const part of words.segment(text)) {
    if (part.isWordLike) total += 1;
  }
  return total;
}
JS

cat > main.js <<'JS'
import { countWords } from './format.js';

const status = document.querySelector('#status');
const notes = document.querySelector('#notes');
const count = document.querySelector('#count');

function updateCount() {
  count.textContent = `${countWords(notes.value)} words`;
}
notes.addEventListener('input', updateCount);
updateCount();

status.textContent = `Modules are running. Top-level this is ${this}.`;
JS

Three things about type="module" matter here:

  • It is deferred. The script tag sits in the <head>, above the text box, yet main.js can find #notes. A module script waits until the HTML has been parsed, as if it had the defer attribute, so you do not need a DOMContentLoaded listener or a script at the bottom of <body>.
  • It is strict. Module code always runs in strict mode. At the top level this is undefined rather than window, and a typo such as totl = 1 throws a ReferenceError instead of quietly creating a global variable. The last line of main.js prints this so you can see it.
  • Imports use URLs. './format.js' is resolved against the URL of main.js. The ./ and the .js extension are both required; the browser does not guess file names the way Node and bundlers can.

format.js counts words with Intl.Segmenter, which knows the word rules of each language. Splitting on spaces works for English, French or Hausa, but not for languages such as Thai or Japanese that do not put spaces between words, and the segmenter handles those too.

Check it worked

ls ~/modules-demo lists format.js, index.html and main.js.

Step 2 · Open it from disk and see it fail

Open index.html straight from the folder: drag it into a browser window, or run open index.html on macOS or xdg-open index.html on Linux. The address bar starts with file://.

The heading and the text box appear, but the status line still says Modules have not run. and no word count shows. Open the developer tools console (F12, or Cmd and Option and I on a Mac). In Chrome and Edge you see an error that says the script was blocked by CORS policy, with origin null.

The reason is that module scripts are always fetched with CORS (cross-origin resource sharing) rules, even when they come from the same place as the page. A page opened from file:// has no proper origin, so Chromium-based browsers refuse to load any module for it. Other browsers have their own rules for file://, and they change between versions, so do not rely on any of them. Serve the folder over HTTP.

Check it worked

The page from file:// still reads Modules have not run., and the console shows one red error mentioning CORS for main.js.

Step 3 · Serve the folder over HTTP

Any static web server will do, as long as it sends .js files with a JavaScript content type: browsers refuse to run a module served as text/plain or application/octet-stream. Use http-server from npm. Open a second terminal, because the server keeps running in the foreground:

Bash
cd ~/modules-demo
npx http-server@14.1.1 -p 8080 -c-1

npx may ask to download the package first; answer y. -p 8080 picks the port and -c-1 turns off caching, so every reload fetches the files you just edited instead of a stale copy. The server prints the addresses it listens on and keeps running until you press Ctrl+C.

Back in the first terminal, ask the server for main.js and look at the content type it sends:

Bash
curl -sI http://localhost:8080/main.js | grep -i '^content-type'
curl -sI http://localhost:8080/main.js | grep -iq '^content-type: .*javascript'

Check it worked

curl prints a content-type line with javascript in it, something like content-type: application/javascript; charset=utf-8. Open http://localhost:8080/ in your browser: the status line reads Modules are running. Top-level this is undefined. and under the text box you see 13 words. Type in the box and the count changes as you type.

Step 4 · Vendor a library and map it with an import map

Now add the Markdown preview. Most npm packages are written to be imported by name, as in import { marked } from 'marked'. In a browser that name is a bare specifier: it is not a URL, so on its own the browser cannot resolve it and throws an error saying something like Failed to resolve module specifier "marked".

An import map fixes that. It is a small JSON block in the page that maps names to URLs. Rather than point it at a CDN, keep a copy of the library in your own vendor folder, so the site does not depend on a third-party server being up and the version cannot change under you. marked publishes a single self-contained ES module file, lib/marked.esm.js, which makes it a good fit. Download it with npm and copy that file plus the licence:

Bash
cd ~/modules-demo
npm init -y > /dev/null
npm install marked@18.2.1
mkdir -p vendor
cp node_modules/marked/lib/marked.esm.js vendor/marked.esm.js
cp node_modules/marked/LICENSE vendor/marked-LICENSE

Write a module that turns Markdown into HTML:

Bash
cd ~/modules-demo
cat > preview.js <<'JS'
import { marked } from 'marked';

export function renderPreview(markdown, target) {
  target.innerHTML = marked.parse(markdown);
}
JS

marked does not clean the HTML it produces. Here the only person typing is the person looking at the preview, so that is fine. If you ever render Markdown that other people wrote, pass the output through a sanitiser such as DOMPurify before it goes into innerHTML.

Now rewrite index.html with the import map, a button and a place for the preview. The import map must come before any module script that uses the names in it:

Bash
cd ~/modules-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Notes</title>
  <script type="importmap">
  {
    "imports": {
      "marked": "./vendor/marked.esm.js"
    }
  }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Notes</h1>
    <p id="status">Modules have not run.</p>
    <label for="notes">Your notes (Markdown)</label><br>
    <textarea id="notes" rows="8" cols="40">## Meeting notes

- Agree the **launch date**
- Translate the page into French and Hausa</textarea>
    <p id="count" aria-live="polite"></p>
    <button type="button" id="show-preview">Show preview</button>
    <div id="preview"></div>
  </main>
</body>
</html>
HTML

cat > main.js <<'JS'
import { countWords } from './format.js';
import { renderPreview } from './preview.js';

const status = document.querySelector('#status');
const notes = document.querySelector('#notes');
const count = document.querySelector('#count');
const button = document.querySelector('#show-preview');
const preview = document.querySelector('#preview');

function updateCount() {
  count.textContent = `${countWords(notes.value)} words`;
}
notes.addEventListener('input', updateCount);
updateCount();

button.addEventListener('click', () => {
  renderPreview(notes.value, preview);
});

status.textContent = `Modules are running. Top-level this is ${this}.`;
JS

The value ./vendor/marked.esm.js is resolved against the page's URL, so it works wherever the folder is served from. When you upgrade, install the new version, copy the file again and reload. When you deploy, copy index.html, the .js files and vendor/; the node_modules folder and package.json only exist to download the library.

Check it worked

curl -s http://localhost:8080/vendor/marked.esm.js | head -n 2 prints a comment that starts with marked v18.2.1. Reload http://localhost:8080/ and click Show preview: below the button, Meeting notes appears as a heading, followed by a bulleted list with launch date in bold. The console has no errors.

Step 5 · Remove the request waterfall with modulepreload

Think about what the browser does with this page. It reads the HTML and finds only main.js. It can only find out about format.js and preview.js once main.js has arrived and been parsed, and it can only find out about marked.esm.js once preview.js has arrived. That is three round trips one after another before the page works. On a fast office connection you will not notice. On a mobile connection where each round trip takes 200 to 400 milliseconds, which is common on 3G and busy 4G networks, it adds up to a visible delay.

<link rel="modulepreload"> tells the browser about a module before anything imports it. The browser fetches and parses it straight away, all in parallel, and uses that copy when the import is reached. Unlike a plain preload, it also prepares the file as a module, so it is not downloaded twice. The href is a URL, not a name from the import map. Add one hint per module:

Bash
cd ~/modules-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Notes</title>
  <script type="importmap">
  {
    "imports": {
      "marked": "./vendor/marked.esm.js"
    }
  }
  </script>
  <link rel="modulepreload" href="./main.js">
  <link rel="modulepreload" href="./format.js">
  <link rel="modulepreload" href="./preview.js">
  <link rel="modulepreload" href="./vendor/marked.esm.js">
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Notes</h1>
    <p id="status">Modules have not run.</p>
    <label for="notes">Your notes (Markdown)</label><br>
    <textarea id="notes" rows="8" cols="40">## Meeting notes

- Agree the **launch date**
- Translate the page into French and Hausa</textarea>
    <p id="count" aria-live="polite"></p>
    <button type="button" id="show-preview">Show preview</button>
    <div id="preview"></div>
  </main>
</body>
</html>
HTML

The cost of this hint is upkeep: the list has to match your imports by hand. Leave a module out and you get the waterfall back for that file; leave a removed module in and the browser downloads a file nobody uses.

Check it worked

In your browser, open the developer tools, select the Network panel, tick Disable cache and set the throttling menu to a slow 3G or 4G preset. Reload. The four .js requests start at about the same moment, side by side in the waterfall column, instead of as a staircase. Delete the four modulepreload lines in your editor, reload, and the staircase returns. Put them back before moving on.

Step 6 · Load the preview only when it is needed

Preloading makes the preview download faster, but everyone still downloads it, including people who never click the button. marked.esm.js alone is about 52 KB before compression. For someone on a prepaid data bundle on a low-end Android phone, code they never use is money and battery spent for nothing.

The dynamic form, import('./preview.js'), is a function-like call that returns a promise. Nothing is fetched until that line runs, so put it in the click handler. Remove the static import of preview.js from main.js and load it on the first click instead. The browser keeps loaded modules, so later clicks reuse the same copy without another request:

Bash
cd ~/modules-demo
cat > main.js <<'JS'
import { countWords } from './format.js';

const status = document.querySelector('#status');
const notes = document.querySelector('#notes');
const count = document.querySelector('#count');
const button = document.querySelector('#show-preview');
const preview = document.querySelector('#preview');

function updateCount() {
  count.textContent = `${countWords(notes.value)} words`;
}
notes.addEventListener('input', updateCount);
updateCount();

button.addEventListener('click', async () => {
  button.disabled = true;
  try {
    const { renderPreview } = await import('./preview.js');
    renderPreview(notes.value, preview);
  } catch (error) {
    preview.textContent = 'The preview could not load. Check your connection and try again.';
    console.error(error);
  } finally {
    button.disabled = false;
  }
});

status.textContent = `Modules are running. Top-level this is ${this}.`;
JS

The try and catch matter more than they look. A static import that fails stops the whole page; a dynamic one fails only when someone clicks, perhaps after their connection dropped. The message tells them what happened and the button works again for a retry.

Now take the preview and marked out of the preload hints. Preloading them would download them on page load again and undo the point of this step. Keep the hints for the modules every visitor needs:

Bash
cd ~/modules-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Notes</title>
  <script type="importmap">
  {
    "imports": {
      "marked": "./vendor/marked.esm.js"
    }
  }
  </script>
  <link rel="modulepreload" href="./main.js">
  <link rel="modulepreload" href="./format.js">
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Notes</h1>
    <p id="status">Modules have not run.</p>
    <label for="notes">Your notes (Markdown)</label><br>
    <textarea id="notes" rows="8" cols="40">## Meeting notes

- Agree the **launch date**
- Translate the page into French and Hausa</textarea>
    <p id="count" aria-live="polite"></p>
    <button type="button" id="show-preview">Show preview</button>
    <div id="preview"></div>
  </main>
</body>
</html>
HTML

The import map stays. preview.js still imports marked by name when it finally loads, and the map is what resolves that name.

Check it worked

In the Network panel, with Disable cache still ticked, reload the page. The JavaScript requests are main.js and format.js only. Click Show preview: two new rows appear, preview.js and then marked.esm.js, and the formatted preview shows below the button. Click it again: no new rows appear.

Step 7 · Check the page with a browser script

Checking by eye works once. A short script checks the same things every time you change the page. Install Playwright, which drives a real browser from Node, into the demo folder. --with-deps also installs the system libraries Chromium needs on Linux and may ask for your password:

Bash
cd ~/modules-demo
npm install playwright@1.65.1
npx playwright install --with-deps chromium

The script opens the page from disk to confirm it fails, then from the server, and records every request the page makes:

Bash
cd ~/modules-demo
cat > check-page.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';

const browser = await chromium.launch();

// 1. From disk: the module is blocked, so the status line never changes.
const fromDisk = await browser.newPage();
const diskErrors = [];
fromDisk.on('console', (msg) => { if (msg.type() === 'error') diskErrors.push(msg.text()); });
await fromDisk.goto(new URL('./index.html', import.meta.url).href);
await fromDisk.waitForTimeout(1000);
assert.equal(await fromDisk.locator('#status').textContent(), 'Modules have not run.');
console.log('file:// error:', diskErrors[0] ?? '(none logged)');

// 2. Over HTTP, recording which files are requested.
const page = await browser.newPage();
const requested = [];
page.on('request', (req) => requested.push(new URL(req.url()).pathname));
await page.goto('http://localhost:8080/');

// Module scripts are deferred and strict.
await page.getByText('Modules are running. Top-level this is undefined.').waitFor();
assert.equal(await page.locator('#count').textContent(), '13 words');

// The preview code has not been downloaded yet.
await page.waitForLoadState('networkidle');
assert.ok(requested.includes('/format.js'), 'format.js loaded');
assert.equal(requested.filter((p) => p === '/format.js').length, 1, 'preloaded module fetched once');
assert.ok(!requested.includes('/preview.js'), 'preview.js not loaded before the click');
assert.ok(!requested.includes('/vendor/marked.esm.js'), 'marked not loaded before the click');

// One click loads it, and the bare specifier "marked" resolves through the import map.
await page.getByRole('button', { name: 'Show preview' }).click();
await page.getByRole('heading', { name: 'Meeting notes', level: 2 }).waitFor();
assert.equal(await page.locator('#preview strong').textContent(), 'launch date');
assert.ok(requested.includes('/preview.js'), 'preview.js loaded after the click');
assert.ok(requested.includes('/vendor/marked.esm.js'), 'marked loaded from vendor/');

// A second click reuses the loaded modules.
const before = requested.length;
await page.getByRole('button', { name: 'Show preview' }).click();
await page.waitForLoadState('networkidle');
assert.equal(requested.slice(before).filter((p) => p.endsWith('.js')).length, 0, 'no new JS requests');

await browser.close();
console.log('PASS: modules, import map and lazy preview work');
JS
node check-page.mjs

getByRole('heading', { level: 2 }) finds the ## Meeting notes line only after marked has turned it into an <h2>, so that one line proves the import map, the dynamic import and the library all worked.

Check it worked

The output starts with a file:// line that quotes the browser's CORS error, and the last line is PASS: modules, import map and lazy preview work. To watch it fail for the right reason, add <link rel="modulepreload" href="./preview.js"> back into index.html and run node check-page.mjs again: it stops with an AssertionError saying preview.js not loaded before the click. Remove the line and it passes again.

Step 8 · Decide whether to stay build-free

You now have a page with no build step at all: what you write is what the browser runs. That is a real advantage. There is no build tool to install, upgrade or debug, and anyone who can edit a file and reload can work on it.

It stays a good choice while all of these hold:

  • You write plain JavaScript and CSS. Browsers cannot run TypeScript, JSX or Vue and Svelte component files.
  • The page has tens of modules, not hundreds. Every file is a request, and the preload list is kept by hand.
  • Your dependencies are few and ship a single-file ES module build, like marked does. Many npm packages are hundreds of small files or still CommonJS, and do not load in a browser as they are.
  • You are happy to serve files without minification or content-hashed names. A bundler shrinks files and gives them names that change when the content does, so browsers can cache them for a year.

When one of those stops being true, move to Vite. Your code barely changes: the import and export lines are the same standard syntax, the import map goes away because Vite resolves marked from node_modules, and import('./preview.js') becomes a separate file in the build automatically. Start a plain JavaScript project with Vite walks through that setup.

Check it worked

Take one project you work on, or plan to build, and go through the four conditions above. You can say which, if any, it fails. If it fails none, a folder like ~/modules-demo served by any static host is enough; if it fails one, you know which feature of a build tool you need.

Step 9 · Stop the server and clean up

In the terminal running http-server, press Ctrl+C to stop it. Then remove the demo folder, which also removes marked and the local Playwright install. The browser Playwright downloaded stays in its shared cache; npx playwright uninstall removes it if you no longer need it.

Bash
cd ~
rm -rf ~/modules-demo

Check it worked

ls ~/modules-demo reports that there is no such file or directory, and http://localhost:8080/ in your browser no longer loads.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Digital Transformation

Get new tutorials

New tutorials, about twice a month.