无法附加到自定义Web组件
我有一个根级别的Web组件。其简化版本如下所示:
class AppLayout {
constructor() {
super();
this.noShadow = true;
}
connectedCallback() {
super.connectedCallback();
this.render();
this.insertAdjacentHTML("afterbegin", this.navigation);
}
render() {
this.innerHTML = this.template;
}
get template() {
return `
<h1>Hello</h1>
`;
}
navigation = `
<script type="module">
import './components/nav-bar.js'
</script>
`;
}
customElements.define('app-layout', AppLayout);
我想在此组件加载后加载脚本。该脚本创建用于导航的HTML,并尝试将其添加到上面显示的App-Layout
元素中。但是,尽管它确实找到了app-layout
元素,但它无法附加navbar
元素。但是,它可以将navbar
附加到HTML的body
。我缺少的任何想法。
const navLinks =
`<ul>
<li>Some</li>
<li>Links</li>
</ul>
`;
const navBar = document.createElement('nav');
navBar.innerHTML = navLinks;
const appLayout = document.querySelector('app-layout'); // works with 'body' but not with 'appLayout'
console.log(appLayout); // Logs correct element
appLayout.appendChild(navBar);
我知道我要在这里尝试做的事情(在Web组件中加载脚本)并不理想,但是,我仍然想了解为什么以上内容不起作用。
I have a web-component at root level. The simplified version of which is shown below:
class AppLayout {
constructor() {
super();
this.noShadow = true;
}
connectedCallback() {
super.connectedCallback();
this.render();
this.insertAdjacentHTML("afterbegin", this.navigation);
}
render() {
this.innerHTML = this.template;
}
get template() {
return `
<h1>Hello</h1>
`;
}
navigation = `
<script type="module">
import './components/nav-bar.js'
</script>
`;
}
customElements.define('app-layout', AppLayout);
I want to load a script after this component loads. The script creates html for navigation and tries to add it to the app-layout
element shown above. However, even though, it does find the app-layout
element, it is unable to append the navBar
element. It is, however, able to append the navBar
to the body
of the html. Any ideas what I'm missing.
const navLinks =
`<ul>
<li>Some</li>
<li>Links</li>
</ul>
`;
const navBar = document.createElement('nav');
navBar.innerHTML = navLinks;
const appLayout = document.querySelector('app-layout'); // works with 'body' but not with 'appLayout'
console.log(appLayout); // Logs correct element
appLayout.appendChild(navBar);
I know that what I'm trying to do here (loading a script inside a web component) is not ideal, however, I would like to still understand why the above doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
InnerHtml
或在您的情况下insertadjacenthtml
将&lt; script&gt;
标记添加到文档中不起作用,因为历史上试图防止潜在的交叉浏览器站点脚本攻击( https://www.w3.org/tr/2008/wd-html5-20080610/dom.html#innerhtml0 )您能做的就是这样的事情:
using
innerHTML
or in your caseinsertAdjacentHTML
to add<script>
tags to the document doesn't work because browsers historically try to prevent potential cross site script attacks (https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0)What you could do is something like: