正在加载,请稍候…

HTMX: Build Modern Web Apps Without a JavaScript Framework

Learn how HTMX enables AJAX, CSS transitions, WebSockets, and SSE directly in HTML. Build interactive web applications with server-side rendering and minimal JavaScript.

HTMX: Build Modern Web Apps Without a JavaScript Framework

HTMX lets you access modern browser features directly from HTML, enabling AJAX requests, WebSockets, and SSE without writing JavaScript.

Core Attributes

  • hx-get, hx-post, hx-put, hx-delete - HTTP methods
  • hx-target - where to put the response
  • hx-swap - how to swap content
  • hx-trigger - when to make the request

Getting Started

<script src="https://unpkg.com/htmx.org@1.9.10"></script>

<button hx-get="/api/message" hx-target="#result">
  Click Me
</button>

<div id="result"></div>

Triggers

<!-- Debounced search -->
<input hx-get="/api/search"
       hx-trigger="keyup changed delay:300ms"
       hx-target="#results"
       name="q"
       placeholder="Search...">

<!-- Load on scroll into view -->
<div hx-get="/api/items?page=2"
     hx-trigger="intersect once"
     hx-target="#item-list"
     hx-swap="beforeend">
</div>

<!-- Poll every 5 seconds -->
<div hx-get="/api/stock-price"
     hx-trigger="every 5s"
     hx-target="this">
</div>

Server Side: Return HTML, Not JSON

const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: true }));

let todos = [
  { id: 1, text: "Buy groceries", done: false },
];

// Return HTML fragments
app.get('/todos', (req, res) => {
  const html = todos.map(todo => `
    <li id="todo-${todo.id}">
      <input type="checkbox" ${todo.done ? 'checked' : ''}
             hx-put="/todos/${todo.id}/toggle"
             hx-target="#todo-${todo.id}"
             hx-swap="outerHTML">
      <span>${todo.text}</span>
    </li>
  `).join('');
  res.send(html);
});

app.post('/todos', (req, res) => {
  const todo = { id: Date.now(), text: req.body.text, done: false };
  todos.push(todo);
  
  res.send(`
    <li id="todo-${todo.id}">
      <span>${todo.text}</span>
    </li>
  `);
});

Out-of-Band Swaps

<!-- Server can update multiple areas in one response -->
<!-- Main content -->
<div id="main-content">
  Dashboard loaded
</div>

<!-- Out-of-band: update header too -->
<div id="header" hx-swap-oob="true">
  Updated: 2024-01-15
</div>

When to Use HTMX

HTMX shines for:

  • CRUD applications: Admin panels, dashboards
  • Server-rendered apps: Django, Rails, Laravel, Express
  • Progressive enhancement: Works without JS enabled

Consider React/Vue when you need:

  • Complex client-side state
  • Rich interactive UI components
  • Offline capabilities

Summary

HTMX reduces JavaScript complexity for server-rendered apps. By returning HTML fragments instead of JSON, you keep UI logic on the server while gaining SPA-like interactivity.