durgesh.patle durgesh.patle - 5 months ago 49
Javascript Question

Javascript not executing inside shadow DOM

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="button" onclick="loadTemplate()" value="Load template">
<div id="template-holder"></div>
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);

And test-template.html will look like this:

<div>Hello from template</div>

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

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.


To make the 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;


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