Search code examples
javascript

function in my javascript module is not defined


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


Solution

  • 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?