How to load a javascript module with jquery
Asked Answered
D

3

10

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

Disconnected answered 5/11, 2019 at 16:42 Comment(3)
Bear in mind import isn't supported by any of the MS browsers. Your likely going to want to use something like webpack to transpile your code into something with better support.Vincentia
Thank you @Vincentia . Let's say my application runs only on chrome: is there a way to solve my problem?Disconnected
Well one issue is, module.js does not include the code for library.js. So you can't just load that one js file. Again precompilation should solve this as it can bundle the whole application into one file. I'd still be looking at webpack or some other compilerVincentia
M
1

Try loading the script in the html file as

  <script type="module" src="module.js"></script>
Motorize answered 4/5, 2020 at 23:33 Comment(2)
Actually the point of my question is loading modules using javascript because I take the list of modules from a DB :-)Disconnected
Did you solve this ever? I'm running into the same issue.Lam
N
0

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.

Nuncupative answered 5/5, 2022 at 6:18 Comment(0)
T
0

This worked for me:

I put an empty placeholder for the Script in HTML:

&lt;script id="loadlater" type="module"&gt;&lt;/script&gt;

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

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

Tocology answered 21/11, 2023 at 17:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.