-->

Javascript not executing inside shadow DOM

2019-07-29 23:22发布

问题:

I am working on an application where I've to load other html webpages to current page. Other webpages are independent applications. I am trying to load webpage in shadow DOM. For that I've used below code, where it will try to import test-template.html in shadowRoot. Here I am not using template tag, because I've to render template dynamically (Using ajax).

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  </head>
  <body>
     <input type="button" onclick="loadTemplate()" value="Load template">
     <div id="template-holder"></div>
     <script>
     function loadTemplate() {
      var templateUrl = "test-template.html",
      templateReceivedCallback = function(response) {
         var div = document.getElementById('template-holder'),
            shadowRoot = div.attachShadow({
                mode: 'open'
            });
        shadowRoot.innerHTML = response;
      };
     $.get(templateUrl, templateReceivedCallback);
     }
  </script>
 </body>

And test-template.html will look like this:

  <div>Hello from template</div>

 <script>
     alert("this text is from script inside of template")
 </script>

I am able to load the mentioned test-template.html in my current page, but javascript inside of test-template.html is not executing. Is there any way to make the script run ? If yes, please share the running example. Thanks.

回答1:

To make the <script> active, you should first insert the loaded file in a <template> element. Then use the importNode() method that will clone the content of the template and execute the scripts inside.

Instead of:

shadowRoot.innerHTML = response;

Do:

var template = document.createElement( 'template' )
template.innerHTML = response 
shadowRoot.appendChild( document.importNode( template.content, true ) )