Search code examples
htmldomknockout.jscustom-element

Should I manually register custom knockout elements to the DOM?


In knockout we can create custom elements that can look something like this:

<flight-deals params='from: "lhr", to: "sfo"'></flight-deals>

The definition of custom elements in HTML is still work in progress and a part of the process of using this today is to register the custom element to the DOM using document.registerElement.

However, I can not find anything in the knockout documentation regarding these aspects, and when I investigate if my custom elements are registered to the DOM by knockout after calling ko.components.register, they turn out not to be.

So if I'm using custom elements in knockout, should I also make sure to also register these manually using document.registerElement? The fact that knockout does not already do this makes me a little confused.


Solution

  • You don't need to do anything special for modern browsers and IE9+.

    For IE6 - IE8 support you do need to be aware of this and use a wee bit of magic. As the relevant documentation mentions:

    • HTML5-era browsers, which includes Internet Explorer 9 and later, automatically allow for custom elements with no difficulties.
    • Internet Explorer 6 to 8 also supports custom elements, but only if they are registered before the HTML parser encounters any of those elements.

    IE 6-8’s HTML parser will discard any unrecognized elements. To ensure it doesn’t throw out your custom elements, you must do one of the following:

    • Ensure you call ko.components.register('your-component') before the HTML parser sees any <your-component> elements
    • Or, at least call document.createElement('your-component') before the HTML parser sees any <your-component> elements. You can ignore the result of the createElement call — all that matters is that you have called it.