自定义元素 Web 组件阴影 DOM 供应商 Scripts/Elements
Custom Element Web Component Shadow DOM Vendor Scripts/Elements
使用需要脚本的 Custom Elements that leverage Shadow DOM, what is the official approach to injecting 3rd party scripts and elements such as 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 中使用第三方库的官方方法是什么?由于 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) {
...
}
}
感谢您提供的任何指导。
没有官方方法,因为解决方案取决于第 3 方库的实现。
但是,对于 reCaptcha,解决方法是在普通 DOM 中公开 <button>
,然后通过 <slot>
将其注入 Shadow DOM ]元素。
class extends HTMLElement {
constructor() {
super()
this.attachShadow( {mode: 'open'} ).innerHTML= `
<form>
<slot></slot>
</form>`
}
connectedCallback() {
this.innerHTML = `
<button
class="g-recaptcha"
data-sitekey="your_site_key"
data-callback="onSubmit">Submit</button>`
}
})
使用需要脚本的 Custom Elements that leverage Shadow DOM, what is the official approach to injecting 3rd party scripts and elements such as 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 中使用第三方库的官方方法是什么?由于 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) {
...
}
}
感谢您提供的任何指导。
没有官方方法,因为解决方案取决于第 3 方库的实现。
但是,对于 reCaptcha,解决方法是在普通 DOM 中公开 <button>
,然后通过 <slot>
将其注入 Shadow DOM ]元素。
class extends HTMLElement {
constructor() {
super()
this.attachShadow( {mode: 'open'} ).innerHTML= `
<form>
<slot></slot>
</form>`
}
connectedCallback() {
this.innerHTML = `
<button
class="g-recaptcha"
data-sitekey="your_site_key"
data-callback="onSubmit">Submit</button>`
}
})