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

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. Commented Nov 6, 2019 at 8:26
  • Thank you @Liam . Let's say my application runs only on chrome: is there a way to solve my problem? Commented Nov 6, 2019 at 8:31
  • 1
    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 compiler Commented Nov 6, 2019 at 9:04

3 Answers 3

1

Try loading the script in the html file as

  <script type="module" src="module.js"></script>
Sign up to request clarification or add additional context in comments.

2 Comments

Actually the point of my question is loading modules using javascript because I take the list of modules from a DB :-)
Did you solve this ever? I'm running into the same issue.
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.

Comments

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.