当使用利用Shadow DOM的Custom Elements时,注入第三方脚本和Invisible reCAPTCHA等需要脚本的元素的官方方法是什么:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>`
要呈现 <button>
等HTML元素,还是要渲染reCAPTCHA?
shadowRoot
似乎没有像 head
这样的东西,应该将脚本添加到创建的 template
的 innerHTML
中吗?或 <script>
是通过 connectedCallback()
中的 appendChild
追加到shadowRoot?在Shadow DOM中使用第三方库的官方方法是什么?由于Shadow DOM,在包含渲染的自定义元素的页面上加载脚本似乎不会触发渲染 .
const template = document.createElement('template');
template.innerHTML = `
<form>
<button class="g-recaptcha"
data-sitekey="your_site_key"
data-callback='onSubmit'>Submit</button>
</form>
`;
class CustomElement extends HTMLElement {
constructor() {
super(); // always call super() first in the ctor.
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
connectedCallback() {
...
}
disconnectedCallback() {
...
}
attributeChangedCallback(attrName, oldVal, newVal) {
...
}
}
感谢您提供的任何指导 .
1 回答
没有官方方法,因为解决方案取决于第三方库实现 .
但是,在reCaptcha的情况下,解决方法是在正常DOM中公开
<button>
,并通过<slot>
元素将其注入Shadow DOM .