Javascript not executing inside shadow DOM

为君一笑 提交于 2020-01-05 08:18:12

问题


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 ) )


来源:https://stackoverflow.com/questions/40736326/javascript-not-executing-inside-shadow-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!