[英]Javascript not executing inside shadow DOM
I am working on an application where I've to load other html webpages to current page. 我正在一个应用程序中将其他HTML网页加载到当前页面。 Other webpages are independent applications. 其他网页是独立的应用程序。 I am trying to load webpage in shadow DOM. 我正在尝试在影子DOM中加载网页。 For that I've used below code, where it will try to import test-template.html in shadowRoot. 为此,我使用了以下代码,它将尝试在shadowRoot中导入test-template.html。 Here I am not using template tag, because I've to render template dynamically (Using ajax). 在这里,我不使用模板标记,因为我必须动态渲染模板(使用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: 并且test-template.html将如下所示:
<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. 我可以在当前页面中加载提到的test-template.html,但是test-template.html中的javascript无法执行。 Is there any way to make the script run ? 有什么办法可以使脚本运行? If yes, please share the running example. 如果是,请分享正在运行的示例。 Thanks. 谢谢。
To make the <script>
active, you should first insert the loaded file in a <template>
element. 要激活<script>
,首先应将加载的文件插入<template>
元素中。 Then use the importNode()
method that will clone the content
of the template and execute the scripts inside. 然后使用importNode()
方法将克隆模板的content
并在其中执行脚本。
Instead of: 代替:
shadowRoot.innerHTML = response;
Do: 做:
var template = document.createElement( 'template' )
template.innerHTML = response
shadowRoot.appendChild( document.importNode( template.content, true ) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.