Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function in my javascript module is not defined

Tags:

javascript

I'm writing JavaScript for the browser, my script.js has something like

import { foo, bar } from "./lib/sth.js"
function main() { ... }

Then I have this in my browser:

<script type=module src="./script.js"></script>
<body onload="main();"> ... </body>

But it's keep giving me this error:

Uncaught ReferenceError: main is not defined at onload ((index):7)

Why is my main now defined? It works fine before I use type=module, but with the import statement, I believe it has to be type=module

like image 912
Dmitrii2333 Avatar asked Feb 26 '26 15:02

Dmitrii2333


1 Answers

Thanks for @HereticMonkey and @FelixKling!

window.onload = function() { ... } 

does work for my problem. Yet I'm confused why import is designed like this. Suppose I just wanna use some library in my script so I import it, why this makes my script has to be a module as well?

like image 123
Dmitrii2333 Avatar answered Feb 28 '26 05:02

Dmitrii2333



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!