web-componentlit-elementpolymer-3.x

LitElement load external script


I tried to simply load it in my rendered HTML but this does not work.

current code:

render() {
    return html `<script @onload="${this.mapKitLoadedCallback}" src="https://cdn.apple-mapkit.com/mk/5.x.x/mapkit.js"></script>`;
}

Solution

  • got a solution from polymer slack channel (credit to westbrook):

    import { LitElement, html } from 'lit-element';
    
    class MyElement extends LitElement {
      script() {
        let script = document.createElement('script');
        script.onload = this.onLoad.bind(this);
        script.src = 'https://cdn.apple-mapkit.com/mk/5.x.x/mapkit.js';
        return script;
      }
      onLoad() {
        alert('loaded');
      }
      render() {
        return html`
          <p>Hello world! From my-element</p>
          ${this.script()}
        `;
      }
    }
    
    customElements.define('my-element', MyElement);