MFave
MFave

Reputation: 1074

How to do simple es6 module loading in a browser?

I'm trying to use the feature of new browsers that allows you to load JavaScript modules as apposed to scripts.

Every example of this seems super straight forward. You simply change the type attribute from "text/javascript" to "module".

I have a simple test.js file that just grabs a DOM node and sets its inner HTML to "Hello" :

const output = document.querySelector("#output");
output.innerHTML = "hello";

This works when type = "text/javascript" but fails with type = "module" :

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>JS Modules</title>
  </head>
  <body>
    <main>
      <h1>JS Modules</h1>
      <div id="output"></div>
    </main>
    <script type="module" src="./test.js"></script>
  </body>
</html>

What am I missing?

Upvotes: 2

Views: 172

Answers (1)

Theo
Theo

Reputation: 2042

<script type="module"></script>

is only supported in modern browsers.They're in…

  1. Safari 10.1.
  2. Chrome 61.
  3. Firefox 54 – behind the dom.moduleScripts.enabled setting in about:config.
  4. Edge 16.

other browsers than that, your script won't load

For backwards compatibility, you can add the nomodule script

<script type="module" src="./test.js"></script>
<script nomodule src="fallback.js"></script>

here's a more complete reference https://jakearchibald.com/2017/es-modules-in-browsers/

Upvotes: 1

Related Questions