Script inside shadow dom not working

前端 未结 1 1961
我寻月下人不归
我寻月下人不归 2020-12-10 21:39

I\'ve created and exported one Angular Element (web component in Angular) as a single script tag (user-poll.js). To use this Angular Element I just need to specify below two

相关标签:
1条回答
  • 2020-12-10 22:31

    The fact that the script is not executed is not related to Shadow DOM, but to the way you try to insert the <script> element, that is via a string in innerHTML. In this case the string is not interpreted and the script not executed.

    If you want it to work you must insert the <script> via appendChild().

    You can do it directly by adding a <script> element created with createElement(), or by using a <template> element.

    1. with createElement()

    Create a <script> element and append it to its parent:

    var up = document.createElement( 'user-poll' )
    var script = document.createElement( 'script' )
    script.textContent = 'document.write( "executed" )'
    up.appendChild( script )
    elm.attachShadow( { mode: 'open' } )
       .appendChild( up )
    <div id="elm"></div>

    2. with a <template> tag

    Append the content of a <template> element:

    elm.attachShadow( { mode: 'open' } )
       .appendChild( tpl.content )
    <template id="tpl">
        <user-poll>
            <script>document.write( 'exected' )</script>
        </user-poll>
    </template>
    
    <div id="elm"></div>

    The script is not executed when the <template> element is parsed, but when its content is appended to the DOM.

    PS: anyway I'm not sure it's the best way to load multiple Angular elements: Shadow DOM won't act as a sandbox for Javascript code, as <iframe> does. Instead maybe you'll have to use a module loader.

    0 讨论(0)
提交回复
热议问题