I am constructing a modular web app where various user-created models are to be handled. Shadow DOM is an obvious choice, but I don't understand how JS can be executed within shadow DOM.
I have an HTML content to be loaded with the following dummy scripts.
<h1>Nice header</h1>
<script type="text/javascript">
console.log('hello')
alert('hi');
</script>
I load the page with the previous scripts like this:
<div id="shadow-target"></div>
<div id="non-shadow-target"></div>
<script>
// Called on btn click
loadShadow = function(module) {
var root = document.querySelector('#shadow-target').createShadowRoot();
var lighttarget = document.querySelector('#non-shadow-target');
$.get('whatever.html', function (data) {
alert(data);
$(root).append(data); // Nothing executed
$(lighttarget).append(data); // Works fine
// The header appears in both cases
});
}
</script>
As the ments say, the JS is not executed when the content is inserted into the shadow DOM root. The header appears in both cases but the scripts are executed only in light DOM. Why is that? How can custom JS be executed in the shadow DOM? (No cross domain stuff.)
I am constructing a modular web app where various user-created models are to be handled. Shadow DOM is an obvious choice, but I don't understand how JS can be executed within shadow DOM.
I have an HTML content to be loaded with the following dummy scripts.
<h1>Nice header</h1>
<script type="text/javascript">
console.log('hello')
alert('hi');
</script>
I load the page with the previous scripts like this:
<div id="shadow-target"></div>
<div id="non-shadow-target"></div>
<script>
// Called on btn click
loadShadow = function(module) {
var root = document.querySelector('#shadow-target').createShadowRoot();
var lighttarget = document.querySelector('#non-shadow-target');
$.get('whatever.html', function (data) {
alert(data);
$(root).append(data); // Nothing executed
$(lighttarget).append(data); // Works fine
// The header appears in both cases
});
}
</script>
As the ments say, the JS is not executed when the content is inserted into the shadow DOM root. The header appears in both cases but the scripts are executed only in light DOM. Why is that? How can custom JS be executed in the shadow DOM? (No cross domain stuff.)
This jsfiddle verifies that script execution indeed works inside shadow dom when you are using plain JS. Therefore I don't see a difference between shadow and light dom in terms of script executions.
BUT, if I use jQuery it seems to be ignoring script tags when I append html to shadow root. Here is a jsfiddle for that as well. This seems to be a bug with jquery which repositions script tags, which bined with shadow dom messing up execution of scripts. Here is one of the few links which try to explain this behavior.
So instead of using
$(root).append(clone2);
Use
root.appendChild(clone2);
And script execution should work fine, even in shadow dom.