Search code examples
javascriptkendo-uiweb-componentcustom-elementnative-web-component

Web Component not running using $(document).ready from within the component


I am new to Web Components, and am trying to build a reusable component combining a Kendo UI component with a remote data source. The Kendo component relies on using $(document).ready(function() to initialise it. When I put that code in a component, it never fires.

If i just put the html mark up in the component, and put the script to initialise it in the main code, it works fine. If I put the script in the component: I don't think it ever fires. I have put a console.log int he code to see if I see anything, but zilch. I get no errors on the console, and can't see anything useful that can help me work this out. Component code is below

customElements.define('location-multi-list2', class AppDrawer extends 
HTMLElement {
connectedCallback() {
this.innerHTML = '<div class="demo-section k-content">
        <h4>Dynamic Stores2</h4>
        <select id="hastores2"></select>
    </div>
    <script>
        $(document).ready(function() {
            $("#hastores2").kendoMultiSelect({
                dataTextField: "name",
                dataValueField: "id",
                dataSource: {
                    transport: {
                        read: {
                            dataType: "json",
                            url: "https://myDomain/path/storeList",
                        }
                    },
                    schema : {
                    data: "stores.location"
                    }
                }
            });
        });
    </script>';
}
});

Solution

  • Any <script> added by using .innerHTML will not be run. This is to prevent security risks. For more info you can read the section Security Considerations on this page: https://devdocs.io/dom/element/innerhtml

    Instead you must create a <script> element and fill in with the script:

    class AppDrawer extends HTMLElement {
      connectedCallback() {
        this.innerHTML = `<div class="demo-section k-content">
          <h4>Dynamic Stores2</h4>
          <select id="hastores2"></select>
        </div>`;
        
        let script = document.createElement('script');
        script.textContent = `alert('here');
          $(document).ready(function() {
            $("#hastores2").kendoMultiSelect({
              dataTextField: "name",
              dataValueField: "id",
              dataSource: {
                transport: {
                  read: {
                    dataType: "json",
                    url: "https://myDomain/path/storeList",
                  }
                },
                schema : {
                  data: "stores.location"
                }
              }
            });
          });
    `;    
        this.appendChild(script);
      }
    }
    
    customElements.define('location-multi-list2', AppDrawer);
    <location-multi-list2></location-multi-list2>