【发布时间】:2018-04-23 21:41:46
【问题描述】:
当使用利用Shadow DOM 的Custom Elements 时,注入第三方脚本和元素(如Invisible reCAPTCHA)的官方方法是什么,需要这样的脚本:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>`
要引导 HTML 元素(例如 <button>)并呈现 reCAPTCHA?
shadowRoot 似乎没有head 之类的东西,是不是应该将脚本添加到创建的template 的innerHTML 中?还是通过connectedCallback() 中的appendChild 将<script> 附加到shadowRoot?在 Shadow DOM 中使用 3rd 方库的官方方法是什么?由于 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) {
...
}
}
感谢您提供的任何指导。
【问题讨论】:
标签: recaptcha web-component shadow-dom custom-element