Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

X-Tag and the Web Components Family

In the last few years we've witnessed an evolution in what 'app' means to both developers and consumers. The word app evokes the idea of a rich, task-oriented user experience with highly optimized user interface that responds to its environment and can be used on an array of common devices. In order to make development of rich app experiences easier, native platforms have generated many of their own controls and components that Just Work™.

For other native technology stacks, extensible components are all but assumed - not so much for the web. Soon, that all changes. We are on the verge of a declarative renaissance that will dramatically advance app development for the web platform, and Web Components will drive it.

X-Tag and Web Components offer features that obliterate the status quo for layout, UI, and widget development - here's a few notable Web Component features:

  • Create real custom elements the browser understands
  • Stop the instantiation madness: $$('button.super').initSuperButton()
  • Remove unmanageable HTML widget guts from your app's view files
  • Work with sharable components, based on standard technologies

Meet the Web Components Family

Web Components is a group of W3C specifications, quickly moving toward standardization, that provide a robust HTML component model. You should not assume the following specs are implemented in your browser of choice. While these specifications are in various stages of implementation across browsers, you can use X-Tag (with either Mozilla or Google's polyfill) today to create custom elements that work well in recent version of Firefox, Chrome, Safari, and stock mobile browsers. X-Tag is a powerful sugar library primarily focused on wrapping and enhancing one of the draft-state Web Component specs: Custom Elements (document.register). We'll get to X-Tag shortly - but for now, let's quickly review the key features of each spec.

Custom Elements

Custom Elements provides you a way to create new elements for use in your environment. There are two ways to declare a new custom element, the imperative DOM API - document.register(), and the declarative HTML tag - <element> (whose DOM constructor is HTMLElementElement). After declaration, new custom elements can be created in the same ways native elements are, such as document.createElement, presences in original source (the markup of a page), and innerHTML, etc.

Here's an example of what a custom element registration looks like in both the imperative and declarative styles.

Imperative:

document.register('x-foo', {
  prototype: Object.create(HTMLElement.prototype, {
    readyCallback: { 
      value: function(){
        // do stuff here when your element is created
        this.innerHTML = '<div>Barrrr me matey!</div>';
      }        
    },
    bar: {
      get: function() { return 'bar'; },
    },
    // add more properties to your custom prototype
    // ...
  })
});

Declarative:

<element name="x-foo">
  <script>
    if (this !== window) {
      this.register({
        prototype: {
          readyCallback: {
            value: function(){
              // do stuff here when your element is created
              this.innerHTML = '<div>Barrrr me matey!</div>';
            }        
          },
          bar: {
            get: function() { return 'bar'; },
          }
        }
      });
    }
  </script>
</element>
<element name="x-foo"><script>
    if (this !== window) {
      this.register({
        prototype: {
          readyCallback: { 
            value: function(){
              // do stuff here when your element is created
              this.innerHTML = '
Barrrr me matey!
'; } }, bar: { get: function() { return 'bar'; }, } } }); } </script></element>

Shadow DOM

The Shadow DOM allows you to encapsulate structural and supporting elements within components. Elements within <shadow-root> nodes remain visible for purposes of display UI (depending on the type of element and your styles), but are hidden from the rest of your application code, unless you explicitly cross the shadow boundary.

HTML Templates

HTML Templates bring simple DOM templating and markup reuse to the web platform - which are often shimmed today using the HTMLScriptElement + DocumentFragment hack-pattern.

HTML Imports

HTML Imports are external HTML documents that contain declarative component definitions. HTML component documents can by imported using the link element with the rel attribute value import. Imported resources may themselves contain additional sub-imports, which the browser then retrieves and performs automatic dependency resolution upon.

Web Components + X-Tag = WINNING

Mozilla's X-Tag library enhances the imperative (JavaScript) route for creating custom elements. X-Tag's primary interface is the xtag.register() method - it wraps the soon-to-be standard document.register() DOM API with features and functionality that make development of amazing custom elements effortless.

Creating a Custom Element

Here's a quick example of what registering a custom element looks like using X-Tag:

xtag.register('x-pirate', {
  lifecycle: {
    ready: function(){
      this.innerHTML = '<blockquote>' +
                         '<img src="pirate-1.png"/>Barrr me matey!' +
                       '</blockquote>';
    }
  },
  accessors: {
    src: {
      // X-Tag's attribute sugar relays any value passed to the src
      // setter on to the src attribute of our <x-pirate> and its
      // <img> element (specified by CSS selector), and vice versa.
      attribute: { selector: 'img' },
      set: function(){
        // When a <x-pirate>'s src attribute/setter is changed, we
        // stop everything to announce the arrival of a new pirate.
        // Ex: doc.querySelector('x-pirate').src = 'pirate-2.png';
        alert("There's a new captain on deck ye scurvy dogs!");
      }
    }
  },
  events: {
    // This is an example of X-Tag's event and pseudo systems. The
    // "tap" custom event handles the dance between click and touch,
    // the ":delegate(img)" pseudo ensures our function is only
    // called when tapping the <img> inside our <x-pirate>.
    'tap:delegate(blockquote > img)': function(){
      alert("A pirate's life for me!");
    }
  }
});

Get the Code

Head over to X-Tags.org and grab the code to develop custom elements of your own. After you get the hang of things, start contributing to our open source effort!

 

Document Tags and Contributors

 Last updated by: chrisdavidmills,