是否可以创建任何人都可以使用而无需安装的Web组件?

Tim*_*eng 2 html javascript web-component polymer custom-element

我刚刚开始使用Web组件,如果我理解正确,那么任何人都可以重用它们.是否有可能创建一个任何人都可以使用的组件,只需向他们的静态站点添加一段html(类似于添加JavaScript小部件的方式,只需复制粘贴几行代码),或者是否需要有人安装?或者这不是Web组件的预期用例?

Sup*_*arp 9

是.Web组件是一种"Javascript小部件".

通常,您在Javascript文件中定义Web组件.然后,您可以将其包含在带有<script>元素的任何HTML中.

带有最小自定义元素的示例<hello-world>:

hello-world.js中:

customElements.define( 'hello-world', class extends HTMLElement {
    constructor() {
        super()
        this.attachShadow( {mode: 'open' })
            .innerHTML = 'Hello World!'
    }
} )
Run Code Online (Sandbox Code Playgroud)

在您的主页index.html中:

<html>
    <head>
        <!-- import the web component -->
        <script src="hello-world.js">
    </head>
    <body>
        <!-- use the new element -->
        <hello-world></hello-world>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

注意:或者,也可以将定义自定义元素的Javascript代码复制粘贴到其主HTML页面.