Crate custom_elements[][src]

Expand description

The Web Components standard creates a browser feature that allows you to create reusable components, called Custom Elements.

While web_sys exposes the browser’s CustomElementRegistry interface, it can be hard to use. Creating a Custom Element requires calling customElements.define() and passing it an ES2015 class that extends HTMLElement, which is not currently possible to do directly from Rust.

This crate provides a CustomElement trait that, when implemented, allows you to encapsulate any Rust structure as a reusable web component without writing any JavaScript. In theory it should be usable with any Rust front-end framework.

impl CustomElement for MyWebComponent {
  fn inject_children(&mut self, this: &HtmlElement) {
      inject_style(&this, "p { color: green; }");
      let node = self.view();

  fn observed_attributes() -> &'static [&'static str] {

  fn attribute_changed_callback(
      &mut self,
      _this: &HtmlElement,
      name: String,
      _old_value: Option<String>,
      new_value: Option<String>,
  ) {
      if name == "name" {
          /* do something... */

  fn connected_callback(&mut self, _this: &HtmlElement) {

  fn disconnected_callback(&mut self, _this: &HtmlElement) {

  fn adopted_callback(&mut self, _this: &HtmlElement) {

pub fn define_custom_elements() {



A custom DOM element that can be reused via the Web Components/Custom Elements standard.


Attaches a <style> element with the given content to the element, either to its shadow root (if it exists) or to the custom element itself.

Attaches a <link rel="stylesheet"> element with the given URL to the custom element, either to its shadow root (if it exists) or to the custom element itself.