简体   繁体   中英

script only executed once

I have created a web component and used in two different places as follows.

    <div class="sub_container">

        <label>Users in Debt</label>

        <input placeholder="Search by user name" class="input_style">

        <my-component filter="userdebt"></my-component>


    </div>

    <div class="sub_container">

        <label>Debts</label>

        <input placeholder="Search by debt description" class="input_style">

        <my-component filter="debt"></my-component>

    </div>

</div>

As you can see i have used <my-component filter="userdebt"></my-component> in 2 places.

Here i'll show my web component

        connectedCallback() {
            console.log("ABC");
            window.globalVar = this.getAttribute("filter");


            this.innerHTML = `
    <html>
    <body>
    <div id="templates">
    <template id="book-template">
        <li><span class="title"></span> &mdash; <span class="author"></span></li>
    </template>


    <ul id="books"></ul>

    </div>
    <script type="module" src="./js/testingjs.js"></script>
    </body>
    </html>

    `;

            var yourElement = document.getElementById('templates');
            yourElement.id = globalVar;
            console.log("MyComp ", yourElement.id);


        }

customElements.define('my-component', MyComponent);

But even though i have used my-component twice in the html i can see the console.log only once meaning it's executing only once. What can be the reason for this?

A Javascript ES6 module is only loaded the first time it's needed.

Therefore its content is only executed once (when it is loaded).

You should call explicitly a function defined in the Javascript module in connectedCallback() method if you want it to be exectuted for each custom element created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM