Javascript未在影子DOM中执行 [英] Javascript not executing inside shadow DOM
问题描述
我正在开发一个必须将其他HTML网页加载到当前页面的应用程序.其他网页是独立的应用程序.我正在尝试在影子DOM中加载网页.为此,我使用了下面的代码,它将尝试在shadowRoot中导入test-template.html.这里我不使用模板标签,因为我必须动态渲染模板(使用Ajax).
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>
test-template.html将如下所示:
And test-template.html will look like this:
<div>Hello from template</div>
<script>
alert("this text is from script inside of template")
</script>
我能够在当前页面中加载提到的test-template.html,但是test-template.html中的javascript无法执行.有什么办法可以使脚本运行?如果是,请分享正在运行的示例. 谢谢.
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.
推荐答案
要激活<script>
,首先应将加载的文件插入<template>
元素中.
然后使用importNode()
方法将克隆模板的content
并在其中执行脚本.
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.
代替:
shadowRoot.innerHTML = response;
做:
var template = document.createElement( 'template' )
template.innerHTML = response
shadowRoot.appendChild( document.importNode( template.content, true ) )
这篇关于Javascript未在影子DOM中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!