'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
Solution 1:[1]
Try loading the script in the html file as
<script type="module" src="module.js"></script>
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | rokiuk |
Solution 2 | woif00 |