Running JS in the shadow of the DOM

I am creating a modular web application in which I need to process various user models. Shadow DOM is an obvious choice, but I don’t understand how JS can be executed in shadow DOM.

I have HTML content to download 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 as follows:

<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 you can see from the comments, JS is not executed when the content is pasted into the shadow of the DOM. The title appears in both cases, but the scripts are executed only in the light DOM. Why is this? How can custom JS execute in the shadow of the DOM? (There is no cross domain.)

+4
source share
1 answer

jsfiddle , script shadow dom , plain JS. dom script .

, jQuery, , , script, html root. jsfiddle. , jquery, script, dom . , try .

$(root).append(clone2);

root.appendChild(clone2);

script , dom.

+2

Source: https://habr.com/ru/post/1547704/


All Articles