Benedikt R.
Benedikt R.

Reputation: 83

Javascript-modules and Web-Component

I'd like to define a Webcomponent in a Javascript-Module and call a method of this component.

The browser raises an Javascript-error: "helloworld" is not a function.

Strange: If I load the Javascript-File "normally" and not as a module, the function is called.

How can I make it run as a Javascript-Module?

This is the JavaScript-Module main.js:

customElements.define('hello-world', 
  class MyComponent extends HTMLElement {     
    helloworld() {
        console.log("Hello World");
    }
});

This is the HTML-Code:

<!DOCTYPE html>
<html>
  <head>
    <script type="module" src="main.js"></script> 
  </head>
  <body>
    <hello-world></hello-world>
    <script>
      var instance = document.querySelector( 'hello-world' );
      instance.helloworld();
    </script>
  </body>
</html>

Loading Javascript with

<script src="main.js"></script> 

works.

Upvotes: 3

Views: 1277

Answers (1)

Benedikt R.
Benedikt R.

Reputation: 83

Problem is: Modules are alway loaded asyc and are alway executed after the DOM is loaded. Therefore the Web-Component is not yet defined when it's instanciated in HTML.

This code works, since the inline-module is executed after the extern module.

<!DOCTYPE html>
<html>
  <head>
    <title>simple demo</title>
    <script type="module" src="main.js"></script>
  </head>
  <body>
    <hello-world></hello-world>
    <script type="module" >
      var  instance = document.querySelector('hello-world');
      instance.helloworld();
    </script>
  </body>
</html>

Upvotes: 2

Related Questions