Daniele Pallastrelli
Daniele Pallastrelli

Reputation: 2552

How to load a javascript module with jquery

I'm loading a javascript file using jquery with the usual:

// file application.js
$.getScript("module.js", function(data, textStatus, jqxhr) { ... });

So far so good. Except that module.js uses a function declared in another module i.e., it contains the statement:

// file module.js
import { myFunction } from './library.js';

When the browser loads my application, it complains that:

Cannot use import statement outside a module

Is there a way to load the script module.js as a module?

Thanks

Upvotes: 10

Views: 3313

Answers (3)

Cem Edisboylu
Cem Edisboylu

Reputation: 1

This worked for me:

I put an empty placeholder for the Script in HTML:

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

and later with jquery I loaded it by setting the src attribute:

$("script#loadlater").attr("src","/js/myModuleScript.js");

Upvotes: 0

woif00
woif00

Reputation: 1

You cannot load other modules unless you declare your own script also a module.

So if your javascript is inline code you can do:

<script type="module"> ... $.getScript("module.js", function(data, textStatus, jqxhr) { ... }); ... </script>

The problem I ran into using this approach is, while using jQuery you also have to also import jQuery as Module.

There's another thread on how to do that here I liked the solution from Yukulélé.

Depending on how many other scripts you have this might be a load of work, or if you're using a lot of external scripts this might not work at all.

Upvotes: 0

rokiuk
rokiuk

Reputation: 11

Try loading the script in the html file as

  <script type="module" src="module.js"></script>

Upvotes: 1

Related Questions