Florian Schulz explores a way to define a web component entirely via markup.
For me, HTML is sort of a component format. So far we’ve used it to define everything that is required for a website to work. But because components are just smaller versions of that, HTML may be a capable format for authoring web components. You don’t need to learn how to write a constructor for a
CustomElement
and then figure out a way to write your multi-line template as a string or usingcreateElement()
all over the place. All you need is your knowledge about HTML as a document format.
The code covered in the technical writeup is all still exploratory, but I do like the fact that it would become as easy as this to load web components:
<head>
<link rel="import" href="custom-search.html">
</head>
<body>
<custom-search value="dog food"></custom-search>
<script src="runtime.js"></script>
</body>
(that included runtime.js
is a polyfill to load and run the component)
The imported custom-search.html
file contains all stuff needed for the web component to work:
<html>
<head>
<title>custom-search</title>
</head>
<body value placeholder>
<!-- Component Markup: -->
<form>
<!-- … -->
</form>
<!-- Component Styles: -->
<style>
/* … */
</style>
<!-- Component Logic: -->
<script>
// …
</script>
</body>
</html>
With this approach, these HTML Components can be opened as a standalone page, directly in the browser. See this color picker for example, which is used in this demo.
Self-contained components aye? I like this. A lot. 🙂
Why don’t we use HTML to author web components? →
Import CustomElements from HTML files (Technical Writeup) →
~
As the author notes: In Custom Elements v0 there was a thing called HTML Imports, but those are deprecated and eventually got removed from Chrome in 2020. Don’t know the specific reasoning, so feel free to enlighten me on that part 🙂
Update 2021.11.30: Thanks to reader Steren for pointing to Mozilla’s position on HTML Imports which might explain the deprecation:
Mozilla anticipated that JavaScript modules would change the landscape here and would rather invest in evolving that, e.g., through HTML Modules.
So instead of HTML Imports they wanted to pursue implementing HTML Modules, similar to how CSS Modules and JSON Modules work.