Skip to main content

jan 11, 2025

# Web components and Eleventy

The curse and the beauty of Eleventy is that there are a many ways to achieve something. At the same time web components lend themselves to be handled pretty freely because after all, it's just client-side JavaScript.

Eleventy guides you in their docs to use WebC, which is their most recommended way to handle web components and offers some benefits like compatibility with server-side rendering and a more structured way to handle web components.

But the beauty of web components should be that they are framework agnostic, and you can just copy and paste the CSS and javascript file to any project and they will work.

<script src="src/js/my-component.js"></script>
<link rel="stylesheet" href="src/css/my-component.css" />

<my-component></my-component>

It can be that simple. But if you want to just have some basic page size optimization and load the CSS and JS only when the component is present, you can use the following snippet.

{% for component in components %}
  {% set component_css_url = "src/css/" + component + ".css" %}
  {% set component_js_url = "src/js/" + component + ".js" %}
  {%- css %}{% include component_css_url %}{%- endcss %}
  {%- js %}{% include component_js_url %}{% endjs %}
{% endfor %}

And then in the front matter of the markdown file you can specify which components to load.

---
title: "Web components and Eleventy"
components: ["my-component"]
---

# Resources