Search code examples
javascriptecmascript-6es6-modules

ES6 Modules: Undefined onclick function after import


I am testing ES6 Modules and want to let the user access some imported functions using onclick:

test.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Module Test</title>
</head>
<body>
    <input type="button" value="click me" onclick="hello();"/>
    <script type="module">import {hello} from "./test.js";</script>
</body>
</html>

test.js:

export function hello() {console.log("hello");}

When I click the button, the developer console says: ReferenceError: hello is not defined. How can I import functions from modules so that they are available as onclick functions?

I am using Firefox 54.0 with dom.moduleScripts.enabled set to true.


Solution

  • It's 2025. You can use inline imports to acheive this :)

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Module Test</title>
    </head>
    <body>
        <input 
            type="button" 
            value="click me" 
            onclick="import('/js/test.js').then(Module => Module.hello())" 
        />
    </body>
    </html>
    

    One thing to note is that test.js won't be fetched by the browser until the user clicks the button. So it'll add a little bit of latency. But on the other hand, users who don't click the button won't have unnecessarily fetched the test.js script.

    If you expect that the script will most likely be needed, you can always prefetch it with

    <link rel="prefetch" href="/js/test.js" />
    

    in the <head>