0

Consider this basic function in /js/foo.mjs:

export function foo( ) {
    console.log('Hello, Modularity!');
};

How to import foo function inside an HTML document, so it can be used inline?

<html>
    <head>
        <script type=module src=/js/foo.mjs></script>
    </head>
    <body>
        <button onclick=foo()>Modules are Cool</button>
    </body>
</html>

Yes, I just can define the function in window object:

window['foo'] = function _foo( ) {
    console.log('Hello, Whatever!');
};

But this is something I want to avoid; maybe there is a way to somehow import a function or a variable so it will be accessible inside the whole HTML document?

I guess I can do this:

onclick='import { foo } from "/js/foo.mjs"; foo()'

But this is ugly as hell.

3
  • 1
    Inline event handlers are "ugly as hell" too in my opinion... Why not use addEventListener? Commented Nov 7, 2019 at 19:06
  • 2
    This making no sense, it's like saying "I want global variables but don't want global variables" Commented Nov 7, 2019 at 19:09
  • @DanStarns man, I have bipolar disorder. Commented Nov 7, 2019 at 19:10

0

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.