【问题标题】:Javascript not executing inside shadow DOMJavascript 未在 shadow DOM 内执行
【发布时间】:2017-04-05 19:14:30
【问题描述】:

我正在开发一个应用程序,我必须将其他 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>

我能够在当前页面中加载提到的 test-template.html,但 test-template.html 中的 javascript 没有执行。有没有办法让脚本运行?如果是,请分享运行示例。 谢谢。

【问题讨论】:

    标签: javascript jquery web-component shadow-dom html5-template


    【解决方案1】:

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

    代替:

    shadowRoot.innerHTML = response;
    

    做:

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

    【讨论】:

    • 感谢您的回答,并支持您的回答:p
    • 这似乎不再起作用了...我没有收到 console.log 打印或警报。类 ViewMedia 扩展 HTMLElement { constructor() { super(); const shadow = this.attachShadow({mode: 'open'}); // initElem(shadow, this.getAttribute('data-value')); var template = document.createElement('template'); template.innerHTML = ''; shadow.appendChild(document.importNode(template.content, true));控制台日志(阴影);返回;
    • @mike 你应该发布另一个问题,因为它不是同一个问题
    猜你喜欢
    • 1970-01-01
    • 2021-04-17
    • 2020-05-09
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 2013-10-02
    • 2017-07-02
    相关资源
    最近更新 更多