Why Every Web Developer Should Know HTMX?

Bridging the Gap Between Classic HTML and Modern Front-End Technologies

ยท

7 min read

Why Every Web Developer Should Know HTMX?
Play this article

Introduction

In an era dominated by front-end frameworks like React, Angular, Vue, and Svelte simplicity can often feel like a lost art. Enters HTMX - a lightweight, yet powerful, javascript library that dares to reimagine the way we think about modern web development.

So what is HTMX?, lets deep dive into the world of HTMX for the next few minutes and explore everything about its key features and breathing new life into the increasingly complex landscapes of front-end development.

What is HTMX?

What if you could supercharge your HTML with AJAX requests, CSS transitions, web socket, and server-side events capabilities directly from HTML attributes? That's what HTMX can do for you.

HTMX is small (approx 14k min.gz in size), dependency-free, extendable, and IE11 compatible. Yes you heard me right it is compatible with IE11

No more IE11 meme

Why Choose HTMX?

  • Simplicity and Ease of Learning: HTMX allows you to add dynamic and interactive content directly within HTML without any need to write custom JavaScript. Making it easier for developers who are more comfortable with HTML and CSS.
    It's especially helpful for newcomers to web development or server-side developers wanting to add a little front-end magic.

  • Server-Side Rendering Friendly: HTMX is designed to work well with server-renders HTML, making it a good fit for projects that rely on server-side frameworks like Django, and PHP.

  • Rapid Prototyping: The simplicity of HTMX makes it well-suited for quickly prototyping dynamic behavior without having to set up a full front-end development environment.

Core Concepts and Terminology

HTMX makes HTML extensible, more interactive and thus turning static HTML into "hypertext", which is HTML with behaviors and dynamic capabilities.

  • AJAX: HTMX makes it easier to use AJAX right within HTML, without writing JavaScript code

  • WebSockets: Support of Websockets in HTML via HTMX enables real-time data exchange with the server.

  • Server-Sent Events: HTMX supports the protocol for receiving updates from the server over a single HTTP connection, making it easier to build real-time updates into your web app.

  • hx-* Attributes: The hx-* attributes are custom attributes introduced by HTMX to extend HTML tags with dynamic behaviors making it more interactive and extensible. Some of them are hx-get, hx-post, hx-target etc.

  • Event Handling: Event handling in HTMX allows you to manage the lifecycle of HTTP requests, from the moment the event is triggered to the time when the new content is swapped into the DOM, thus adding more interactivity and dynamic behavior to the applications.

Enough with the theoretical part, let's now deep dive into some practical work with some code examples. Before that let's set up HTMX to use further.

Setting up HTMX

HTMX is a dependency-free, browser-oriented javascript library, thus no need for complicated build steps or systems.

  • Via a CDN: The fastest and simplest way is to add the below code to the head tag of your web page.

      <head>
          <script src="https://unpkg.com/htmx.org@1.9.5" integrity="sha384-xcuj3WpfgjlKF+FXhSQFQ0ZNr39ln+hwjN3npfM9VBnUskLolQAcN80McRIVOPuO" crossorigin="anonymous"></script>
      </head>
    
  • Download a copy: The next simplest way is to download htmx.min.js from unpkg.com, add it to the appropriate directory in your project, and include it using <script> tag.

      <head>
          <script src="/path/to/htmx.min.js"></script>
      </head>
    
  • Via NPM: For NPM-based build systems, you can install HTMX via a simple command

      npm install htmx.org
    

    After installing you can run a web server in the root folder of your project by running the below command.

      npx serve htmx
    

Basic Examples and Use Cases

Button Click to Fetch Data

The below example shows how to use HTMX to fetch data from a URL when a button is clicked.

<button hx-get="/fetch/data" hx-trigger="click" >Fetch Data</button>

When the button is clicked, HTMX sends a GET request /fetch/data and replaces the content of the button with the response.

Updating a ToDo List

Suppose you have a ToDo list and you want to mark an item as completed when it's clicked.

<ul id="todo-list">
  <li hx-post="/mark-complete" hx-trigger="click" hx-swap="outerHTML">Buy Milk</li>
  <li hx-post="/mark-complete" hx-trigger="click" hx-swap="outerHTML">Walk the Dog</li>
</ul>

When you click an item, HTMX sends a POST request to /mark-complete and replaces the clicked li element with the new HTML received from the server.

Form Submission

The below example shows how to submit a form using HTMX

<form hx-post="/submit/form" hx-trigger="submit">
  <input type="text" name="username" placeholder="Enter your username">
  <button type="submit">Submit</button>
</form>

When the form is submitted, HTMX sends a POST request to /submit/form with the form data. The form content will be replaced by the server's response.

Some of the other Use Cases can be like:

  1. Live Search

  2. Infinite Scroll

  3. Form Validation

  4. Bulk update

  5. Real-time updates

Advanced Features

HTMX offers several advanced features that make it a powerful tool for developing interactive and dynamic web applications. Below are some of the features.

Partial Updates with hx-select

the hx-select attribute allows you to specify which part of the server's response should be used to update the DOM. The enables you to perform partial page updates and reduce the amount of data transferred over the network.

<div hx-get="/fetch/data" hx-select="#some-element">
  Click to Fetch Partial Data
</div>

Request Indicators

HTMX allows you to add visual indicators that show when a request is in progress. The hx-indicator attribute lets you specify an element that will be displayed during the AJAX call.

<button hx-get="/data" hx-indicator="#loadingSpinner">
    Fetch Data
</button>
<div id="loadingSpinner" style="display:none;">Loading...</div>

Trigger Modifiers

HTMX supports various trigger modifiers like once, delay, and throttle to fine-tune when and how often should be triggered.

<button hx-get="/data" hx-trigger="click delay:500ms">Fetch Data</button>

Lazy Loading

With the hx-trigger attribute set to revealed, HTMX enables lazy loading of content as elements come into view, this can improve performance by reducing initial load times.

<div hx-get="/lazy-load" hx-trigger="revealed">
  <!-- Content will be loaded when this element comes into view -->
</div>

History Management

HTMX provides a way to manipulate browser history. With attributes like hx-push-url, you can change the URL displayed in the browser's address bar after a request, facilitating navigation and bookmarking.

<div hx-get="/new/page" hx-push-url="true">
  Go to New Page
</div>

Based on the above code, when a user clicks on the div, HTMX will snapshot the current DOM and store it before it requests the/new/page. It then does the swap and pushes a new location onto the history stack.

WebSockets

If you wish to establish a Websocket connection in HTMX, you use the ht-ws attribute.

<div hx-ws="connect:wss:/chatroom">
    <div id="chat_room">
        ...
    </div>
    <form hx-ws="send:submit">
        <input name="chat_message">
    </form>
</div>

The connect the declaration establishes the connection and the send declaration tells the form to submit values to the socket on submit.

Comparing HTMX with Other Front-end Libraries/ Frameworks

As compared to some heavyweight frontend frameworks like Angular, React, or Vue, HTMX offers

  • Simple Learning Curve: HTMX has a significantly lower learning curve compared to frameworks like React, Angular, or Vue.

  • Performance: Since HTMX minimizes the need for client-side JavaScript, web pages often load faster and consume less memory.

  • Server Rendering: HTMX naturally embraces server-rendered HTML, making it a good fit for those who prefer this approach.

Integration with Backend Technologies

HTMX is backend-agnostic and can integrate seamlessly with virtually any server-side language or framework such as Django, Ruby on Rails, Flask, and others.

You can easily couple RESTful APIs or GraphQL endpoints, giving you flexible options for data fetching and manipulation.

HTMX native support of WebSockets and Server-Side events allows integration of real-time features.

Community & Ecosystem

While growing in popularity, its community is smaller compared to established frameworks like React, Angular, Vue, or Svelte. With vast community and documentation resources, the above-mentioned frameworks are widely used and are a go-to choice for many developers.

As HTMX attracts more followers, enthusiasts, and contributors, its community will grow naturally. It is still very young as compared to other front-end frameworks.

๐Ÿš€
HTMX has been accepted into the first class of the GitHub Open Source Accelerator for 2023

Best Practices and Tips

  • Server-Side validation: Take advantage of HTMX's server-side-centric model to handle data validation on the server, making the client lighter and more secure.

  • Utilize Event Hooks: Make the most of HTMX's lifecycle events for fine-grained control over requests and DOM updates.

Limitations of HTMX

Like any other tool, library, or framework we use, HTMX also has limitations, and some of them are listed below.

  • Limited tooling and No Type safety can make debugging a lot more difficult as compared to other frameworks.

  • "JS-in-HTML" approach has been in development earlier also with JS libraries and frameworks like Alpine, Knockout

  • Not ideal for SPAs

  • Lack of Virtual DOM: HTMX does not use virtual DOM, which can sometimes make complex UI updates less efficient.

  • No architectural approach for complex applications.

Conclusion

While growing in popularity, HTMX is carving its niche, offering simpler yet powerful alternatives to other widely used frontend libraries and frameworks. It is quite good for smaller projects and in the end, everything comes down to the project requirements and its complexity.

I hope you have learned something new as I did. If so, kindly like and share the article and also follow me to read more exciting articles. You can check my social links here.

References

HTMX Docs & Examples

ย