Skip to main content

Tagged “webcomponents”

Web Component GitHub Starter Template, by David Darnes

David’s template provides not just the starter component code but also a nice readme, issue template, and publish-to-NPM flow.

It’s also always interesting to see how different developers structure their web component JavaScript. David’s code includes a neat and interesting approach to registering the comoponent, and favours setup being written in the connectedCallback().

Here are a couple of his real web components which started from the template:

Incidentally, I noticed the comment querying where event listeners should go and referencing Hawk Ticehurst’s article You're (probably) using connectedCallback wrong. While their seems to be a degree of validity there, I’m not going to sweat it. I’ve checked Keith Cirkel’s advice on this, which is:

If your component has additional set up logic, like adding event listeners, then the constructor() isn't the best place for that - as the Web Component isn't yet inserted into (or connected) to a DOM tree, and so it won't have a parent. For that, you'll need a lifecycle callback.

I note that even Hawk Ticehurst isn’t 100% sure about the constructor approach.

So I’m gonna go with putting event listeners in callbacks per Keith and David’s approach.

Shoelace: a forward-thinking library of web components

I’m interested by Shoelace’s MO as a collection of pre-rolled, customisable web components. The idea is that it lets individuals and teams start building with web components – components that are web-native, framework-agnostic and portable – way more quickly.

I guess it’s a kind of Bootstrap for web components? I’m interested to see how well it’s done, how customisable the components are, and how useful it is in real life. Or if nothing else, I’m interested to see how they built their components!

It’s definitely an interesting idea.

I'll delve into Shoelace in more detail in the future when I have time, but in the meantime I was able to very quickly knock together a codepen that renders a Dropdown instance.

Thanks to Chris Ferdinandi for sharing Shoelace.

Web Components Guide

This new resource on Web Components from Keith Cirkel and Kristján Oddsson of GitHub (and friends) is looking great so far.

As I recently tweeted, I love that it’s demoing “vanilla” Web Components first rather than using a library for the demos.

So far I’ve found that the various web component development frameworks (Lit etc) are cool, but generally I’d like to see more demos that create components without using abstractions. The frameworks include dependencies, opinions and proprietary syntax that (for me at least) make an already tricky learning curve more steep so they’re not (yet) my preferred approach. Right now I want to properly understand what’s going on at the web standards level.

Aside from tutorials this guide also includes a great Learn section which digs into JavaScript topics such as Classes and Events and why these are important for Web Components.

I hope that in future the guide will cover testing Web Components too.

Lastly, I like the Embed Mastodon Toot web component tutorial, and to help it sink in (and save the code for posterity) I’ve chucked the code into a pen.

Nordhealth’s Design System

There’s so much to admire in Nord Health’s Design System and specifically its reference website.

I love the way it looks and is organised.

There’s a fantastic, practical accessibility checklist.

They document their naming conventions and the rationale behind them.

They were a trailblazer in adopting web components and I love the docs explaining why.

We’ve chosen to use Web Components because there is a strong requirement for Nord to be used in many different contexts and with varying technologies — from static HTML pages to server-rendered apps, through to single page applications authored with frameworks such as React and Vue. Web Components work great for Nord, because they:

  • Are tech-agnostic instead of tech-specific
  • Future proof our system with Web Standards
  • Allow us to use any framework or no framework at all
  • Provide great encapsulation for styles and functionality

Lastly their components look great and show a really high-level of front-end and accessibility literacy.

Let's talk about web components (by Brad Frost)

Brad breaks down the good, bad and ugly of web components but also makes a compelling argument that we should get behind this technology.

I come from the Zeldman school of web standards, am a strong proponent of progressive enhancement, care deeply about accessibility, and want to do my part to make sure that the web lives up to its ideals. And I bet you feel similar. It’s in that spirit that I want to see web components succeed. Because web components are a part of the web!

I’m with you, Brad. I just need to find practical ways to make them work.

WebC

WebC, the latest addition to the Eleventy suite of technologies, is focused on making Web Components easier to use. I have to admit, it took me a while to work out the idea behind this one, but I see it now and it looks interesting.

Here are a few of the selling points for WebC, as I see them.

With WebC, web components are the consumer developer’s authoring interface. So for example you might add a badge component into your page with <my-badge text='Lorem ipsum'></my-badge>.

Using web components is great – especially for Design Systems – because unlike with proprietary component frameworks, components are not coupled to a single technology stack but rather are platform and stack-agnostic, meaning they could be reused across products.

From the component creator perspective: whereas normally web components frustratingly require writing accompanying JavaScript and depending on JavaScript availability even for “JavaScript-free” components, with WebC this is not the case. You can create “HTML-only” components and rely on them to be rendered to screen. This is because WebC takes your .webc component file and compiles it to the simplest output HTML required.

WebC is progressive enhancement friendly. As mentioned above, your no-JS HTML foundation will render. But going further, you can also colocate your foundational baseline beside the scripts and CSS that enhance it within the same file.

This ability to write components within a single file (rather than separate template and script files) is pretty nice in general.

There are lots of other goodies too such as the ability to scope your styles and JavaScript to your component, and to set styles and JS to be aggregated in such a way that your layout file can optionally load only the styles and scripts required for the components in use on the current page.

Useful resources:

Web components as progressive enhancement, by Cloud Four

By enhancing native HTML instead of replacing it, we can provide a solid baseline experience, and add progressive enhancement as the cherry on top.

Great article by Paul Herbert of Oregon’s Cloud Four. Using a web component to enhance an existing HTML element such as <textarea> (rather than always creating a custom element from scratch) feels very lean, resilient and maintainable.

Off the top of my head I could see this being a nice approach for other custom form controls.

Zach Leatherman also took this approach with the <details> element in quite exciting ways and is using it in production on Netlify’s marketing websites. I’m a bit cautious of jumping on that one just yet, though, because it’s plays more fast-and-loose with the intended purpose of the element and in so doing probably might present some accessibility issues. Still really interesting though.

Thanks to @adactio for sharing.

Web Components with Declarative Shadow DOM via Lit and Eleventy

Here’s a new development in the Web Components story, and one that may have positive implications for resilience, performance and progressive enhancement.

Declarative Shadow DOM is a new way to implement and use Shadow DOM directly in HTML rather than by constructing a shadow root in JavaScript.

But some people including Chris Coyier and Brad Frost) reckon that writing that looks horrible. Brad said:

Declarative Shadow DOM always looked gross to me and I felt it almost defeats the purpose of web components.

And Chris added:

the server-side rendering story for Web Components, Declarative Shadow DOM, doesn’t feel very nice to me if you have to do it manually.

However Lit, a library which makes working with Web Components easier, are now providing ways to make this easier when Lit is used with Eleventy.

Brad likes this:

With tools like this (especially this @lit-labs/ssr project), we can have our cake and eat it too: use web components in a dev-friendly way, and then have the machines do the heavy lifting to convert that into a grosser-yet-progressive-enhancement-enabled syntax that ships to the user.

As does Chris:

using JavaScript frameworks in an entirely-client-side rendered way isn’t nearly as good for anything (users, SEO, performance, accessibility, etc) as server-side rendering (the effects of hydration are still debatable, but I view as largely worth it) … [but] the server-side rendering story for Web Components, Declarative Shadow DOM, doesn’t feel very nice to me if you have to do it manually. So… don’t do it manually! Let Eleventy do it!

As an additional footnote, perhaps we can make frameworks other than Eleventy (such as Rails) create server-rendered custom elements with Declarative Shadow DOM in a similar way. One to explore.

Minimum Viable Web Component (by Zach Leatherman)

Zach tweeted last year to share a codepen which illustrates the very simple boilerplate needed for a minimum viable web component. Note: his example is so simple that in this case the JavaScript isn’t actually needed for the custom element to work, however the provided JS is a starting point for when you do actually intend to add JS-driven features.

The HTML:

<foo-component>Hello, world</foo-component>

The CSS:

foo-component {
  font-size: 4em;
}

The JS:

customElements.define("foo-component", class extends HTMLElement {
  constructor() {
    super();
    // Add your custom functionality.
  }
});

What open-source design systems are built with web components?

Alex Page, a Design System engineer at Spotify, has just asked:

What open-source design systems are built with web components? Anyone exploring this space? Curious to learn what is working and what is challenging. #designsystems #webcomponents

And there are lots of interesting examples in the replies.

I plan to read up on some of the stories behind these systems.

I really like Web Components but given that I don’t take a “JavaScript all the things” approach to development and design system components, I’ve been reluctant to consider that web components should be used for every component in a system. They would certainly offer a lovely, HTML-based interface for component consumers and offer interoperability benefits such as Figma integration. But if we shift all the business logic that we currently manage on the server to client-side JavaScript then:

  • the user pays the price of downloading that additional code;
  • you’re writing client-side JavaScript even for those of your components that aren’t interactive; and
  • you’re making everything a custom element (which as Jim Neilsen has previously written brings HTML semantics and accessibility challenges).

However maybe we can keep the JavaScript for our Web Component-based components really lightweight? I don’t know. For now I’m interested to just watch and learn.

My first Web Component: a disclosure widget

After a couple of years of reading about web components (and a lot of head-scratching), I’ve finally got around to properly creating one… or at least a rough first draft!

Check out disclosure-widget on codepen.

See also my pen which imports and consumes the component.

Caveats and to-dos:

  • I haven’t yet tried writing tests for a web component
  • I should find out how to refer to the custom element name in JavaScript without repeating it
  • I should look into whether observedAttributes and attributeChangedCallback are more appropriate than the more typical event listeners I used

References

I found Eric Bidelman’s article Custom Elements v1: Reusable Web Components pretty handy. In particular it taught me how to create a <template> including a <slot> to automatically ringfence the Light DOM content, and then to attach that template to the Shadow DOM to achieve my enhanced component.

Front-end architecture for a new website (in 2021)

Just taking a moment for some musings on which way the front-end wind is blowing (from my perspective at least) and how that might practically impact my approach on the next small-ish website that I code.

I might lean into HTTP2

Breaking CSS into small modules then concatenating everything into a single file has traditionally been one of the key reasons for using Sass, but in the HTTP2 era where multiple requests are less of a performance issue it might be acceptable to simply include a number of modular CSS files in the <head>, as follows:

<link href="/css/base.css" rel="stylesheet">
<link href="/css/component_1.css" rel="stylesheet">
<link href="/css/component_2.css" rel="stylesheet">
<link href="/css/component_3.css" rel="stylesheet">

The same goes for browser-native JavaScript modules.

This isn’t something I’ve tried yet and it’d feel like a pretty radical departure from the conventions of recent years… but it‘s an option!

I’ll combine ES modules and classes

It’s great that JavaScript modules are natively supported in modern browsers. They allow me to remove build tools, work with web standards, and they perform well. They can also serve as a mustard cut that allows me to use other syntax and features such as async/await, arrow functions, template literals, the spread operator etc with confidence and without transpilation or polyfilling.

In the <head>:

<script type="module" src="/js/main.js"></script>

In main.js

import { Modal } from '/components/modal.js';

const Modal = new Modal();
modal.init();

In modal.js

export class Modal {
  init() {
    // modal functionality here
  }
}

I’ll create Web Components

I’ve done a lot of preparatory reading and learning about web components in the last year. I’ll admit that I’ve found the concepts (including Shadow DOM) occasionally tough to wrap my head around, and I’ve also found it confusing that everyone seems to implement web components in different ways. However Dave Rupert’s HTML with Superpowers presentation really helped make things click.

I’m now keen to create my own custom elements for javascript-enhanced UI elements; to give LitElement a spin; to progressively enhance a Light DOM baseline into Shadow DOM fanciness; and to check out how well the lifecycle callbacks perform.

I’ll go deeper with custom properties

I’ve been using custom properties for a few years now, but at first it was just as a native replacement for Sass variables, which isn’t really exploiting their full potential. However at work we’ve recently been using them as the special sauce powering component variations (--gap, --mode etc).

In our server-rendered components we’ve been using inline style attributes to apply variations via those properties, and this brings the advantage of no longer needing to create a CSS class per variation (e.g. one CSS class for each padding variation based on a spacing scale), which in turn keeps code and specificity simpler. However as I start using web components, custom properties will prove really handy here too. Not only can they be updated by JavaScript, but furthermore they provide a bridge between your global CSS and your web component because they can “pierce the Shadow Boundary”, make styling Shadow DOM HTML in custom elements easier.

I’ll use BEM, but loosely

Naming and structuring CSS can be hard, and is a topic which really divides opinion. Historically I liked to keep it simple using the cascade, element and contextual selectors, plus a handful of custom classes. I avoided “object-oriented” CSS methodologies because I found them verbose and, if I’m honest, slightly “anti-CSS”. However it’s fair to say that in larger applications and on projects with many developers, this approach lacked a degree of structure, modularisation and predictability, so I gravitated toward BEM.

BEM’s approach is a pretty sensible one and, compared to the likes of SUIT, provides flexibility and good documentation. And while I’ve been keeping a watchful eye on new methodologies like CUBE CSS and can see that they’re choc-full of ideas, my feeling is that BEM remains the more robust choice.

It’s also important to me that BEM has the concept of a mix because this allows you to place multiple block classes on the same element so as to (for example) apply an abstract layout in combination with a more implementation-specific component class.

<div class="l-stack c-news-feed">

Where I’ll happily deviate from BEM is to favour use of certain ARIA attributes as selectors (for example [aria-current=page] or [aria-expanded=true] because this enforces good accessibility practice and helps create equivalence between the visual and non-visual experience. I’m also happy to use the universal selector (*) which is great for owl selectors and I’m fine with adjacent sibling (and related) selectors.

Essentially I’m glad of the structure and maintainability that BEM provides but I don’t want a straitjacket that stops me from using my brain and applying CSS properly.

Collapsible sections, on Inclusive Components

It’s a few years old now, but this tutorial from Heydon Pickering on how to create an accessible, progressively enhanced user interface comprised of multiple collapsible and expandable sections is fantastic. It covers using the appropriate HTML elements (buttons) and ARIA attributes, how best to handle icons (minimal inline SVG), turning it into a web component and plenty more besides.

HTML with Superpowers (from Dave Rupert)

Here’s a great new presentation by Dave Rupert (of the Shop Talk show) in which he makes a compelling case for adopting Web Components. Not only do they provide the same benefits of encapsulation and reusability as components in proprietary JavaScript frameworks, but they also bring the reliability and portability of web standards, work without build tools, are suited to progressive enhancement, and may pave the way for a better web.

Dave begins by explaining that Web Components are based on not just a set of technologies but a set of standards, namely:

  • Custom Elements (for example <custom-alert>)
  • Shadow DOM
  • ES Modules
  • the HTML <template> element

Standards have the benefit that we can rely on them to endure and work into the future in comparison to proprietary technologies in JavaScript frameworks. That’s good news for people who like to avoid the burnout-inducing churn of learning and relearning abstractions. Of course the pace of technology change with web standards tends to be slower, however that’s arguably a price worth paying for cross-platform stability and accessibility.

Some of Web Components’ historical marketing problems are now behind them, since they are supported by all major browsers and reaching maturity. Furthermore, web components have two superpowers not found in other JavaScript component approaches:

Firstly, the Shadow DOM (which is both powerful and frustrating). The Shadow DOM provides encapsulation but furthermore in progressive enhancement terms it enables the final, enhanced component output which serves as an upgrade from the baseline Light DOM HTML we provided in our custom element instance. It can be a little tricky or confusing to style, however, although there are ways.

Secondly, you can use web components standalone, i.e. natively, without any frameworks, build tools, or package managers. All that’s required to use a “standalone” is to load the <script type=module …> element for it and then use the relevant custom element HTML on your page. This gets us closer to just writing HTML rather than wrestling with tools.

Dave highlights an education gap where developers focused on HTML, CSS, and Design Systems don’t tend to use Web Components. He suggests that this is likely as a result of most web component tutorials focusing on JavaScript APIs for JavaScript developers. However we can instead frame Web Component authoring as involving a layered approach that starts with HTML, adds some CSS, then ends by applying JavaScript.

Web Components are perfectly suited to progressive enhancement. And that progressive enhancement might for example apply lots of complicated ARIA-related accessibility considerations. I really like the Tabs example where one would create a <generic-tabs> instance which starts off with simple, semantic, resilient HTML that renders headings and paragraphs…

<generic-tabs>
  <h2>About</h2>
  <div>
    <p>About content goes here. Lorem ipsum dolor sit amet…</p>
  </div>

  <h2>Contact</h2>
  <div>
    <p>Contact content goes here. Lorem ipsum dolor sit amet…</p>
  </div> 
</generic-tabs>

…but the Web Component’s JavaScript would include a template and use this to upgrade the Light DOM markup into the final interactive tab markup…

<generic-tabs>
  <h2 slot="tab" aria-selected="true" tabindex="0" role="tab" id="generic-tab-3-0" aria-controls="generic-tab-3-0" selected="">About</h2>
  <div role="tabpanel" aria-labelledby="generic-tab-3-0" slot="panel">
    <p>About content goes here. Lorem ipsum dolor sit amet…</p>
  </div>
  <h2 slot="tab" aria-selected="false" tabindex="-1" role="tab" id="generic-tab-3-1" aria-controls="generic-tab-3-1">Contact</h2>
  <div role="tabpanel" aria-labelledby="generic-tab-3-1" slot="panel" hidden>
    <p>Contact content goes here. Lorem ipsum dolor sit amet…</p>
  </div>
</generic-tabs>

The idea is that the component’s JS would handle all the complex interactivity and accessibility requirements of Tabs under the hood. I think if I were implementing something like Inclusive Components’ Tabs component these days I’d seriously consider doing this as a Web Component.

Later, Dave discusses the JavaScript required to author a Custom Element. He advises that in order to avoid repeatedly writing the same lengthy, boilerplate code on each component we might use a lightweight library such as his favourite, LitElement.

Lastly, Dave argues that by creating and using web components we are working with web standards rather than building for a proprietary library. We are creating compatible components which pave the cowpaths for these becoming future HTML standards (e.g. a <tabs> element!) And why is advancing the web important? Because an easier web lowers barriers: less complexity, less tooling and setup, less gatekeeping—a web for everyone.

Progressively enhanced burger menu tutorial by Andy Bell

Here’s a smart and comprehensive tutorial from Andy Bell on how to create a progressively enhanced narrow-screen navigation solution using a custom element. Andy also uses Proxy for “enabled” and “open” state management, ResizeObserver on the custom element’s containing header for a Container Query like solution, and puts some serious effort into accessible focus management.

One thing I found really interesting was that Andy was able to style child elements of the custom element (as opposed to just elements which were present in the original unenhanced markup) from his global CSS. My understanding is that you can’t get styles other than inheritable properties through the Shadow Boundary so this had me scratching my head. I think the explanation is that Andy is not attaching the elements he creates in JavaScript to the Shadow DOM but rather rewriting and re-rendering the element’s innerHTML. This is an interesting approach and solution for getting around web component styling issues. I see elsewhere online that the innerHTML based approach is frowned upon however Andy doesn’t “throw out” the original markup but instead augments it.

Container Queries in Web Components | Max Böck

Max’s demo is really clever and features lots of interesting web component related techniques.

I came up with this demo of a book store. Each of the books is draggable and can be moved to one of three sections, with varying available space. Depending on where it is placed, different styles will be applied to the book.

Some of the techniques I found interesting included:

  • starting with basic HTML for each book and its image, title, and author elements rather than an empty custom element, thereby providing a resilient baseline
  • wrapping each book in a custom book-element tag (which the browser would simply treat like a div in the worst case scenario)
  • applying the slot attribute to each of the nested elements, for example slot="title"
  • including a template with id="book-element" at the top of the HTML. This centralises the optimal book markup, which makes for quicker, easier, and less disruptive maintenance. (A template is parsed but not rendered by the browser. It is available solely to be referenced and used by JavaScript)
  • including slots within the template, such as <slot name="title">
  • putting a style block within the template. These styles target the book component only, and include container query driven responsiveness
  • targetting the <book-element> wrapper element in CSS via the :host selector, and applying contain to set it as a container query context
  • targetting a slot in the component CSS using (for example) ::slotted(img)

Thoughts

Firstly, in the basic HTML/CSS, I might ensure images are display: block and use div rather than span for a better baseline appearance should JavaScript fail.

Secondly, even though this tutorial is really nice, I still find myself asking: why use a Web Component to render a book rather than a server-side solution when the latter removes the JS dependency? Part of the reason is no doubt developer convenience—people want to build component libraries in JavaScript if that’s their language of choice. Also, it requires less backend set-up and leads to a more portable stack. And back-end tools for component-based architectures are generally less mature and feature-rich then those for the front-end.

One Web Component specific benefit is that Shadow DOM provides an encapsulation mechanism to style, script, and HTML markup. This encapsulation provides private scope that both prevents the content of the component from being affected by the external document, and keeps its CSS and JS from leaking out… which might be nice for avoiding the namespacing you’d otherwise have to do.

I have a feeling that Web Components might make sense for some components but be neither appropriate nor required for others. Therefore just because you use Web Components doesn’t mean that you suddenly need to feel the need to write or refactor every component that way. It’s worth bearing in mind that client-side JavaScript based functionality comes with a performance cost—the user needs to wait for it to download. So I feel there might be a need to exercise some restraint. I want to think about this a little more.

Other references

Ruthlessly eliminating layout shift on netlify.com, by Zach Leatherman

I love hearing about clever front-end solutions which combine technologies and achieve multiple goals. In Zach’s post we hear how Netlify’s website suffered from layout shift when conditionally rendering dismissible promo banners, and how he addressed this by rethinking the problem and shifting responsibilities around the stack.

Here’s my summary of the smart ideas covered in the post:

  • decide on the appropriate server-rendered content… in this case showing rather than hiding the banner, making the most common use case faster to load
  • have the banner “dismiss” button’s event handling script store the banner’s href in the user’s localStorage as an identifier accessible on return visits
  • process lightweight but critical JavaScript logic early in the <head>… in this case a check for this banner’s identifier existing in localStorage
  • under certain conditions – in this case when the banner was previously seen and dismissed – set a “state” class (banner--hide) on the <html> element, leading to the component being hidden seamlessly by CSS
  • build the banner as a web component, the first layer of which being a custom element <announcement-banner> and the second a JavaScript class to enhance it
  • delegate responsibility for presenting the banner’s “dismiss” button to the same script responsible for the component’s enhancements, meaning that a broken button won’t be presented if that script were to break.

So much to like in there!

Here are some further thoughts the article provoked.

Web components FTW

It feels like creating a component such as this one as a web component leads to a real convergence of benefits:

  • tool-free, async loading of the component JS as an ES module
  • fast, native element discovery (no need for a document.querySelector)
  • enforces using a nice, idiomatic class providing encapsulation and high-performing native callbacks
  • resilience and progressive enhancement by putting all your JS-dependent stuff into the JS class and having that enhance your basic custom element. If that JS breaks, you still have the basic element and won’t present any broken elements.

Even better, you end up with framework-independent, standards-based component that you could share with others for reuse elsewhere, just like Zach did.

Multiple banners

I could see there being a case where there are multiple banners during the same time period. I guess in that situation the localStorage banner value could be a stringified object rather than a simple, single-URL string.

Setting context on the root

It’s really handy to have a way to exert just-in-time control over the display of a server-rendered element in a way that avoids flashes of content… and adding a class to the <html> element offers that. In this approach, we run the small amount of JavaScript required to test a local condition (e.g. checking for a value in localStorage) really early. That lets us process our conditional logic before the element is rendered… although this also means that it’s not yet available in the DOM for direct manipulation. But adding a class to the HTML element means that we can pre-prepare CSS to use that class as a contextual selector for hiding the element.

We’re already familiar with the technique of placing classes on the root element from libraries like modernizr and some font-loading approaches, but this article serves as a reminder that we can employ it whenever we need it.

Handling the close button

Zach’s approach to handling the banner’s dismiss button was interesting. He makes sure that it’s not shown unless the web component’s JavaScript runs successfully which is great, but rather than inject it with JavaScript he includes it in the initial HTML but hidden with CSS, and his method of hiding is opacity.

We use opacity to toggle the close button so that it doesn’t reflow the component when it’s enabled via JavaScript.

I think what Zach’s saying is that the alternatives – inserting the button with JS, or toggling the hidden attribute or its CSS counterpart display:none – would affect geometry causing the browser to perform layout… whereas modifying opacity does not.

I love that level of diligence! Typically I prefer to delegate responsibility for inserting JS-dependent buttons to JavaScript because in comparison to including a button in the server-rendered HTML then hiding it, it feels more resilient and a more maintainable separation of concerns. However as always the best solution depends on the situation.

If I were going down Zach’s route I think I’d replace opacity with visibility since the latter hiding method removes the hidden element from the document which feels more accessible, while still avoiding triggering the reflow that display would.

Side-thoughts

In a server-side scripted application – one using Rails or PHP, for example – you could alternatively handle persisting state with cookies rather than localStorage… allowing you to test for the presence of the cookie on the server then handle conditional rendering of the banner on the server too, rather than needing classes which trigger hiding. I can see an argument for that. Thing is though, not everyone’s working in that environment. Zach has provided a standalone solution.

References

One web component to rule them all? (on Filament Group, Inc.)

Scott Jehl has taken a refreshingly Progressive Enhancement -centric look at Web Components.

this pattern provides a nice hook for adding progressive enhancements to already-meaningful HTML contained in these custom elements, leaving them resilient in the case of of script loading failures and allowing the page to start rendering before the JS happens to run.

He goes further and creates a factory for creating Web Components which allows adding to a single element many small behavioural script enhancements that may or may not relate to each other.

There are also some great notes on polyfilling and the performance upgrade provided by lifecycle callbacks.

And Scott’s wc-experiments repo contains some interesting demos.

Minimalist Container Queries

Scott Jehl’s experimental take on a container/element query aimed at letting us set responsive styles for our elements based on their immediate context rather than that of the viewport.

I made a quick and minimal take on approximating Container/Element Queries using a web component and basic CSS selectors.

The idea is that for any given instance of the <c-q> custom element / web component you would define a scoped custom property which sets the pixel min-widths you’re interested in, like so:

c-q {
  --breakpoints: "400 600 800";
  background: black;
}

Zero to many of those numeric min-width values will appear in the element’s data-min-width HTML attribute based on which (if any) of them the element’s width is equal to or greater than.

You can style the element based on their presence using the ~= attribute selector, like this:

c-q[data-min-width~="400"] { 
  background: green; 
}
c-q[data-min-width~="600"] {
  background: blue;
}

See also Scott’s tweet announcing this which contains some interesting contributions including Heydon’s watched-box.

All of the various JavaScript approaches/experiments are summarised in CSS-Tricks’s article Minimal Takes on Faking Container Queries.

(via @scottjehl)

See all tags.

External Link Bookmark Note Entry Search