1

I have this simple app where I'm tyring to trigger a function inside Javascript module by pressing a html button but it seems to do nothing. I looked at another thread about this same topic but does not seem to work for me. As soon as I take the type="module" off from the script tag it works so it propably has something to do with that. Console gives no errors so I have no idea what I'm doing wrong here.

index.html

<body>
    <button id="test">Click me!</button>
    <script type="module" src="/app.js"></script>
</body>

app.js

document.getElementById("test").addEventListener("click", () => {
    console.log("Hello!");
});
iWillBeMaster
  • 137
  • 10
  • 2
    Is your script running before the elements have been rendered in the document? Try moving your script tag to the bottom of your body – Ryan Wilson Feb 20 '18 at 17:39
  • 1
    try – Tony Dong Feb 20 '18 at 17:40
  • 2
    The html document is processed from top down, and at the moment the script runs there is no such thing as `document.getElementById("test")`, and you will see an error message to that effect in the browser console. – James Feb 20 '18 at 17:40
  • I tried adding the script after the button but it does not seem to work either. – iWillBeMaster Feb 20 '18 at 17:41
  • 2
    type='module' - I don't think that code is suitable for an ES6 module. Try without type param or type='text/javascript' – James Feb 20 '18 at 17:45
  • I don't know much about modules tbh. I wonder however if you need to transpile via Babel, etc before that will work. [This page](https://medium.com/dev-channel/es6-modules-in-chrome-canary-m60-ba588dfb8ab7) says that browser support for the type='module' parameter is limited to "Experimental mode" in Chrome, and only Safari supports it natively. – James Feb 20 '18 at 17:54
  • 1
    https://stackoverflow.com/questions/37624819/es2015-import-doesnt-work-even-at-top-level-in-firefox - I did close this question, but I'm not satisfied the "duplicate" is a duplicate, but you do need to make some changes to your browser settings as James says to get this to work. I've made the change in FF and tested your code and it works fine. @iWillBeMaster. Let me know if that works and I'll close this as the duplicate. – Andy Feb 20 '18 at 18:03
  • 1
    @iWillBeMaster, if any answer helped you solve the problem, do not forget to vote. – Maicon Heck Feb 20 '18 at 18:38

1 Answers1

1

It seems that 2 things are missing:

The import statement on your html document and the export statement on your snippet to allow there to be a module and can to be imported.

export function yourModule() { 
  // ...
 }

<script type="module"> import {yourModule} from './app.js';
 </script>

Look this: https://jakearchibald.com/2017/es-modules-in-browsers/

Also, check if your browser already support the module type.

Maicon Heck
  • 1,002
  • 13
  • 18