简体   繁体   English

在影子DOM中使用第三方脚本

[英]Use of third-party scripts in shadow DOM

I'm in the middle of developing custom elements for basic reusable controls (eg buttons, menus, data tables etc.) I'm aware of the browser support for custom elements and shadow DOMs, but I'm doing good with the available polyfills in general. 我正在为基本的可重用控件(例如按钮,菜单,数据表等)开发自定义元素,我知道浏览器对自定义元素和阴影DOM的支持,但是我对可用的polyfill做得很好一般来说。

For some custom elements I use third-party scripts for extra functionality but sometimes they don't work as intended when they have to manipulate the DOM in some way. 对于某些自定义元素,我使用第三方脚本来提供其他功能,但有时它们在必须以某种方式操作DOM时无法按预期工作。

That happens every time an external script wants to search for an element by class or id. 每当外部脚本想要按类或ID搜索元素时,就会发生这种情况。 Obviously the call 显然是电话

document.getElementById (id)

or 要么

document.getElementsByClassName (class)

doesn't work because the element with the id or class cannot be found in the global DOM but in the shadow DOM. 之所以不起作用,是因为在全局DOM中只能在影子DOM中找到具有id或class的元素。

As far as I know, you can't give the document variable a new reference in javascript. 据我所知,您无法在javascript中为document变量提供新的引用。

So, is there a solution to this problem without parsing the whole script and rewriting it to become usable in a shadow DOM context? 因此,是否有解决此问题的解决方案,而无需解析整个脚本并将其重写以在影子DOM上下文中可用?

EDIT: It's not about getting elements from shadow DOMs in general but how 3rd-party scripts can be used that don't know that they have to search in the shadow DOM they are called from and not in the main DOM. 编辑:一般而言,这不是要从影子DOM中获取元素,而是如何使用不知道它们必须在从其调用的影子DOM中而不是在主DOM中进行搜索的第三方脚本。 As pointed out in the comments by CBroe. 正如CBroe的评论所指出的那样。

A workaround is to pull the element the 3rd party library needs to catch out of the Shadow DOM. 一种解决方法是将第3方库需要从Shadow DOM中捕获的元素提取出来。

<your-element>
  <div id="visible-id" class="visible-class"></div>
</your-element>

And insert it in the Shadow DOM using the <slot> element. 并使用<slot>元素将其插入Shadow DOM。

Note: I've used a direct, HTML, example but you can insert the callable element by script when your custom element is created: 注意:我已经使用了直接的HTML示例,但是您可以在创建自定义元素时按脚本插入可调用元素:

connectedCallback () {
    this.innerHTML = '<div id="visible-id"></div>'
}  

Of course it's not really in the Shadow DOM but it will work with most of the 3rd-party libraries. 当然,它并不是在Shadow DOM中真正使用的,但是它可以与大多数第三方库一起使用。

You could also choose not to use Shadow DOM at all depending on your needs. 您还可以根据需要选择完全不使用Shadow DOM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM