惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
T
The Blog of Author Tim Ferriss
Scott Helme
Scott Helme
P
Proofpoint News Feed
D
Docker
The Hacker News
The Hacker News
云风的 BLOG
云风的 BLOG
Vercel News
Vercel News
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Project Zero
Project Zero
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
GbyAI
GbyAI
Jina AI
Jina AI
P
Proofpoint News Feed
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
C
CERT Recently Published Vulnerability Notes
博客园 - 叶小钗
U
Unit 42
博客园_首页
Apple Machine Learning Research
Apple Machine Learning Research
Latest news
Latest news
T
The Exploit Database - CXSecurity.com
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
T
Threatpost
V
Vulnerabilities – Threatpost
C
Cisco Blogs
Spread Privacy
Spread Privacy
Cisco Talos Blog
Cisco Talos Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Visual Studio Blog
G
GRAHAM CLULEY
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - Franky
G
Google Developers Blog
Know Your Adversary
Know Your Adversary
F
Fortinet All Blogs
H
Hackread – Cybersecurity News, Data Breaches, AI and More
NISL@THU
NISL@THU
N
Netflix TechBlog - Medium
Y
Y Combinator Blog
L
Lohrmann on Cybersecurity
C
CXSECURITY Database RSS Feed - CXSecurity.com
Recent Announcements
Recent Announcements
量子位
S
Schneier on Security
I
Intezer
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Darknet – Hacking Tools, Hacker News & Cyber Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building Accessible, Performant Web Components: A Practical Frontend Pattern Guide
Rizwan Saleem · 2026-06-04 · via DEV Community

Building Accessible, Performant Web Components: A Practical Frontend Pattern Guide

Building Accessible, Performant Web Components: A Practical Frontend Pattern Guide

In this tutorial, you’ll learn a concrete pattern for creating reusable, accessible, and high-performance web components that work across frameworks or vanilla HTML. We’ll walk through a real-world example: a customizable user profile card component with accessible keyboard navigation, responsive styling, and solid performance practices. You’ll get code patterns, tests, and deployment tips you can adapt to many frontend projects.

Overview and goals

  • Build a self-contained, reusable web component (custom element) that exposes a clean API.
  • Ensure accessibility (ARIA, keyboard navigation, proper focus management).
  • Optimize for performance (shadow DOM boundaries, lazy rendering, minimal reflows).
  • Provide theming and responsiveness without coupling to a specific framework.
  • Include tests and a small build/dev setup to run locally.

Key outcomes

  • A drop-in profile-card web component you can ship in multiple apps.
  • Clear separation between component logic, styling, and data.
  • A guide to extending the component with additional slots, props, or micro-interactions.

    Tech stack (minimal and framework-agnostic)

  • Vanilla JavaScript (Web Components API)

  • Shadow DOM for encapsulation

  • CSS variables for theming

  • ARIA semantics for accessibility

  • Optional: unit tests with Vitest or Jest, and a lightweight bundler (esbuild)

    Step 1: Create the Web Component skeleton

Code pattern: a self-contained custom element with observed attributes and a simple API surface.

  • Expose data via attributes and a JSON-like data attribute for richer content.
  • Use the shadow DOM to isolate styles.
  • Provide a public API method to update content imperatively.

Code (src/ProfileCard.js):

class ProfileCard extends HTMLElement {
  static get observedAttributes() {
    return ['name', 'title', 'avatar', 'bio', 'location'];
  }

  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this._name = '';
    this._title = '';
    this._avatar = '';
    this._bio = '';
    this._location = '';
    this._render();
  }

  attributeChangedCallback(name, oldVal, newVal) {
    if (oldVal === newVal) return;
    switch (name) {
      case 'name': this._name = newVal; break;
      case 'title': this._title = newVal; break;
      case 'avatar': this._avatar = newVal; break;
      case 'bio': this._bio = newVal; break;
      case 'location': this._location = newVal; break;
    }
    this._render();
  }

  setProfile(data) {
    // data shape: { name, title, avatar, bio, location }
    this._name = data?.name ?? this._name;
    this._title = data?.title ?? this._title;
    this._avatar = data?.avatar ?? this._avatar;
    this._bio = data?.bio ?? this._bio;
    this._location = data?.location ?? this._location;
    this._render();
  }

  _render() {
    const name = this._name || 'Unknown';
    const title = this._title || '';
    const avatar = this._avatar;

    // Basic fallback image if none provided
    const avatarEl = avatar
      ? `<img src="${escapeAttr(avatar)}" alt="" class="avatar" referrerpolicy="no-referrer"/>`
      : `<div class="avatar placeholder" aria-label="No avatar"></div>`;

    const bio = this._bio ? `<p class="bio">${escapeHtml(this._bio)}</p>` : '';

    this.shadowRoot.innerHTML = `
      <style>
        :host {
          display: block;
          font-family: system-ui, -apple-system, "Segoe UI", Roboto, Arial;
          color: var(fw-text, #111);
        }
        .card {
          display: grid;
          grid-template-columns: 72px 1fr;
          gap: 12px;
          align-items: center;
          padding: 12px;
          border-radius: 12px;
          background: var(fw-surface, #fff);
          box-shadow: 0 1px 3px rgba(0,0,0,.08);
          transition: transform .2s ease;
        }
        .card:hover { transform: translateY(-1px); }
        .avatar, .placeholder {
          width: 72px; height: 72px; border-radius: 50%;
          overflow: hidden; display: block;
          background: #ddd;
        }
        .avatar { object-fit: cover; }
        .content { display: grid; gap: 6px; }
        .name { font-weight: 700; font-size: 1.05rem; margin: 0; }
        .title { font-size: .9rem; color: #555; margin: 0; }
        .bio { margin: 0; color: #444; font-size: .9rem; }
        @media (max-width: 520px) {
          .card { grid-template-columns: 60px 1fr; padding: 10px; }
          .avatar { width: 60px; height: 60px; }
        }
      </style>
      <section class="card" role="region" aria-label="Profile card">
        <div class="avatar-wrap" aria-label="Avatar">
          ${avatarEl}
        </div>
        <div class="content">
          <p class="name" aria-label="Name">${escapeHtml(name)}</p>
          ${title ? `<p class="title" aria-label="Title">${escapeHtml(title)}</p>` : ''}
          ${bio}
          ${this._location ? `<p class="location" aria-label="Location" style="margin:0;color:#666;font-size:.85rem;">${escapeHtml(this._location)}</p>` : ''}
        </div>
      </section>
    `;
  }
}

function escapeHtml(str) {
  return String(str)
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;');
}
function escapeAttr(str) {
  return String(str).replaceAll('"', '&quot;').replaceAll('?', '');
}

customElements.define('profile-card', ProfileCard);

Enter fullscreen mode Exit fullscreen mode

Usage (HTML):

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8"/>
    <title>Profile Card Demo</title>
  </head>
  <body>
    <profile-card id="pc"></profile-card>

    <script type="module">
      import './src/ProfileCard.js';
      const pc = document.getElementById('pc');
      pc.setProfile({
        name: 'Alex Rivera',
        title: 'Frontend Engineer',
        avatar: 'https://example.com/alex.jpg',
        bio: 'Loves accessible design and tiny perf wins.',
        location: 'Carlisle, England'
      });
    </script>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode

Notes

  • The component uses a shadow DOM to encapsulate styles and prevent leakage.
  • The API is intentionally simple: attribute-based data plus a setProfile method for richer data.
  • Escaping is essential to avoid injection; the helper functions handle it.

    Step 2: Accessibility basics

  • Use aria-labels on interactive parts and meaningful text in the content.

  • If the component becomes actionable, ensure keyboard support (Tab navigation, Enter/Space to trigger).

  • Manage focus when content changes to avoid confusing users.

Enhancement: make the card focusable and provide a details toggle.

Code snippet (augment _render and add a details button):

_render() {
  // ... existing setup
  const detailsId = 'details-' + Math.random().toString(36).slice(2, 7);
  this.shadowRoot.innerHTML = `
    <style> ... </style>
    <section class="card" role="region" aria-label="Profile card" tabindex="0" aria-describedby="${detailsId}">
      ...
      ${bio}
      ${this._location ? `<p id="${detailsId}" class="location" ...>${escapeHtml(this._location)}</p>` : ''}
      <button class="details-btn" aria-controls="profile-details" aria-expanded="false" type="button">More</button>
      <div id="profile-details" hidden>
        <p>Additional details or social links could go here.</p>
      </div>
    </section>
  `;
  // add keyboard/interaction
  const card = this.shadowRoot.querySelector('.card');
  const btn = this.shadowRoot.querySelector('.details-btn');
  const details = this.shadowRoot.querySelector('#profile-details');
  btn.addEventListener('click', () => {
    const expanded = btn.getAttribute('aria-expanded') === 'true';
    btn.setAttribute('aria-expanded', String(!expanded));
    details.hidden = expanded;
  });
  card.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' || e.key === ' ') {
      btn.click();
      e.preventDefault();
    }
  });
}

Enter fullscreen mode Exit fullscreen mode

This approach provides a keyboard-accessible toggle and keeps the card navigable with the keyboard.

Step 3: Theming and design tokens

Support CSS variables for theming so the consumer can adapt the look without touching JS.

  • fw-surface: card background
  • fw-text: main text color
  • fw-muted: secondary text color
  • radius: corner radius
  • shadow: shadow

Usage in HTML:

<profile-card id="pc" style="fw-surface: #fff; fw-text: #111; radius: 14px;"></profile-card>

Enter fullscreen mode Exit fullscreen mode

Or provide a simple theming API:

setTheme({ surface: '#fff', text: '#111', muted: '#555' }) {
  this.style.setProperty('fw-surface', surface);
  this.style.setProperty('fw-text', text);
  this.style.setProperty('fw-muted', muted);
}

Enter fullscreen mode Exit fullscreen mode

Step 4: Data handling patterns

  • Prefer a single, immutable data object for complex content.
  • Accept a JSON string attribute as a compact payload for SSR or markup-driven apps.

Example: accept a data-profile attribute containing JSON.

Attribute parsing in constructor/observed:

attributeChangedCallback(name, oldVal, newVal) {
  if (name === 'data-profile') {
    try {
      const data = JSON.parse(newVal);
      this.setProfile(data);
      return;
    } catch { /* ignore if invalid */ }
  }
  // existing
}

Enter fullscreen mode Exit fullscreen mode

Usage:

<profile-card id="pc" data-profile='{"name":"Alex","title":"Frontend Engineer","avatar":"https://...","bio":"..." ,"location":"Carlisle"}'></profile-card>

Enter fullscreen mode Exit fullscreen mode

Step 5: Performance considerations

  • Shadow DOM boundaries help isolate styles; avoid large DOM trees inside the shadow root.
  • Use lazy loading for images when optional or heavy; add loading="lazy" on avatar images.
  • Minimize re-renders: debounce or batch attribute changes if you call setProfile frequently.
  • Prefer immutable updates: replace innerHTML entirely only when necessary to avoid partial paints.

Code tip: only re-render on meaningful data changes; track a dirty flag if you plan to update in response to rapid sequences.

Step 6: Testing the component

  • Unit tests: verify rendering output given different data, attribute changes, and public API calls.
  • Accessibility tests: ensure aria-labels exist, the toggle is keyboard-accessible, and the DOM structure remains sane.

Example (Vitest/Jest-like pseudo):

import { expect, test, beforeEach } from 'vitest';
import '../src/ProfileCard.js';

beforeEach(() => {
  document.body.innerHTML = `<profile-card id="pc"></profile-card>`;
});

test('renders name and title from attributes', () => {
  const el = document.getElementById('pc');
  el.setAttribute('name', 'Alex');
  el.setAttribute('title', 'Engineer');
  const shadow = el.shadowRoot;
  expect(shadow.querySelector('.name').textContent).toBe('Alex');
  expect(shadow.querySelector('.title').textContent).toBe('Engineer');
});

test('aria-expanded toggles on details button', () => {
  const el = document.getElementById('pc');
  el.setProfile({ name: 'Alex' });
  const btn = el.shadowRoot.querySelector('.details-btn');
  btn.click();
  expect(btn.getAttribute('aria-expanded')).toBe('true');
});

Enter fullscreen mode Exit fullscreen mode

If you’re using a bundler, wire up esbuild/vite with a test script to run these tests in Node environments.

Step 7: How to ship and re-use

  • Publish as a small npm package if you want to share across apps. Pack the component as a library with a nice build step that outputs an ES module and a UMD build for older environments.
  • Document the API clearly: how to instantiate, how to update data, and how to theme.
  • Provide a minimal example app in the repo to showcase usage in vanilla HTML, React, Vue, and Svelte (via a lightweight wrapper or simply using the web component in the template).

Example package.json scripts (minimal):

{
  "name": "profile-card-wc",
  "type": "module",
  "version": "0.1.0",
  "scripts": {
    "build": "esbuild src/ProfileCard.js bundle outfile=dist/profile-card.js format=esm",
    "test": "vitest run"
  },
  "devDependencies": {
    "esbuild": "^0.17.0",
    "vitest": "^0.34.0",
    "happy-dom": "^7.0.0"
  }
}

Enter fullscreen mode Exit fullscreen mode

Note: If you don’t want to publish, you can keep it in a monorepo or a private module and consume via local paths.

Step 8: Extending the component

  • Slots for additional content (e.g., social links)
  • Props for more data (email, website, badges)
  • List-based variants (compact, verbose) controlled via an attribute like variant="compact"

Slot example (HTML in the shadow DOM):

<div class="content">
  <slot name="bio"></slot>
  <slot name="social"></slot>
</div>

Enter fullscreen mode Exit fullscreen mode

Consumer usage:

<profile-card id="pc" name="Alex" title="Engineer">
  <span slot="bio">Custom bio here.</span>
  <span slot="social">Twitter: @alex</span>
</profile-card>

Enter fullscreen mode Exit fullscreen mode

Step 9: Deployment checklist

  • Accessibility: all content reachable by keyboard, landmarks provided, aria attributes in place.
  • Performance: assets lazy-loaded, minimal paint, no layout thrashing.
  • Security: sanitize any data rendered into the DOM; escape attributes and text properly.
  • Documentation: API surface, customization options, and example usage.
  • Testing: unit tests for core behavior and accessibility checks. ### Real-world example: extended usage

Let’s create a profile-card with a responsive variant and an external data source.

HTML (page.html):

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Profile Card Demo</title>
    <script type="module" src="./src/ProfileCard.js"></script>
  </head>
  <body>
    <profile-card id="dev1" variant="compact" data-profile='{"name":"Mira Chen","title":"Frontend Dev","avatar":"https://example.org/mira.jpg","bio":"Accessible by design.","location":"Carlisle"}'></profile-card>

    <script>
      // Optional: rehydrate from an API
      fetch('/api/profile/42')
        .then(r => r.json())
        .then(data => {
          const el = document.getElementById('dev1');
          el.setProfile(data);
        });
    </script>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode

CSS-variable hydration for theme:

<profile-card id="dev1" style="fw-surface:#f9f9fb; fw-text:#1f2937; radius:16px;"></profile-card>

Enter fullscreen mode Exit fullscreen mode

Quick-start checklist

  • [x] Create a self-contained web component with a clean API
  • [x] Encapsulate styles with Shadow DOM and use CSS variables for theming
  • [x] Implement accessible features: ARIA attributes, keyboard support
  • [x] Provide a simple data API (attributes + setProfile)
  • [x] Add basic unit tests for rendering and interactions
  • [x] Document usage and extension points
  • [x] Add a minimal example app to demonstrate usage If you’d like, I can tailor this pattern to a specific project stack you’re using (e.g., React, Svelte, or a pure static site) and provide a ready-to-run repo structure with a small test suite. Do you want the component to expose a slot-based API for additional content or keep it strictly data-driven with a simple public API?

-

Rizwan Saleem | https://rizwansaleem.co

Sources