Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

javascript - Script inside shadow dom not working

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 lines in the host site:

 <user-poll></user-poll>
 <script src="path/to/user-poll.js"></script>

Working JSBin Example

I've following requirements:

  1. Load multiple Angular Elements on the external site.
  2. Load all Angular Elements dynamically

I've following issues:

  1. Loading multiple components on a site gives Angular conflicts, as each component script is a complete Angular app in itself.
  2. To solve conflict issue, I am loading each component in a separate Shadow Dom component (i.e. adding component tag and component script file link inside shadow dom container) so that each component is sandboxed. But component script inside shadow dom not working.

JSBin example of the dynamically loading component inside the shadow dom

<body>

</body>
    setTimeout(() => {
    loadJS();
}, 2000);
function loadJS() {
    var elm = document.createElement("div");
    elm.attachShadow({mode: "open"});
    elm.shadowRoot.innerHTML = `<user-poll><h2>Custom Web Component - user-poll loaded</h2><script src="https://cdn.rawgit.com/SaurabhLpRocks/795f67f8dc9652e5f119bd6060b58265/raw/d5490627b623f09c84cfecbd3d2bb8e09c743ed4/user-poll.js"></script></user-poll>`;
    document.body.appendChild(elm);
}

So, what is the best way to dynamically load multiple Angular Elements on a site?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...