Javascript 未在影子内执行 DOM

Javascript not executing inside shadow DOM

我正在开发一个应用程序,我必须将其他 html 网页加载到当前页面。其他网页是独立的应用程序。我正在尝试在阴影 DOM 中加载网页。为此,我使用了下面的代码,它将尝试在 shadowRoot 中导入 test-template.html。这里我没有使用模板标签,因为我必须动态渲染模板(使用 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>

而 test-template.html 将如下所示:

  <div>Hello from template</div>

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

我可以在当前页面加载提到的测试-template.html,但是测试-template.html 内部的 javascript 没有执行。有没有办法制作脚本 运行 ?如果是,请分享 运行ning 示例。 谢谢

要使 <script> 处于活动状态,您应该首先将加载的文件插入 <template> 元素中。 然后使用 importNode() 方法克隆模板的 content 并执行里面的脚本。

而不是:

shadowRoot.innerHTML = response;

做:

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