19: HTMX(tra), X-tra read all about it!

27 May 2022

We're taking a look at HTMX this week. A really nice small (~10k) open source JS library that can be used from ASP.NET to enhance web apps - add the library, add some attributes to your HTML tags and HTMX magically wires it up for you, performing partial HTML updates by making GET and POST requests.

Random fact

When he first invented it in 1989, Tim Berners-Lee kept the entire World Wide Web (which was still rather small for a time) on his NeXTcube from NeXT, the company started by Steve Jobs after being ousted from Apple.

September 1995, a Netscape programmer named Brandan Eich created it called LiveScript and then later Javascript - wrote it in 10 days!!

There was massive confusion around Javascript vs Java

  • Java ran in Netscape in an applet and is compiled
  • LiveScript was designed to run in the browser and to be interpreted

In 1997 ECMA it was handed to ECMA to manage it properly - European Computer Manufacturers Association

After 10 years could even get to version 4 due to disagreements across browser vendors

2005 Jesse James Garrett introduced a paper introducing ajax - called “Ajax: A New Approach to Web Applications” - pivotal point where different styles of web apps really started to take off - no full page refreshes - partial updates of pages

2008 ECMA version 4 still not agreed, pushed back by many organizations and parties involved with JavaScript, including Yahoo, Google, and Microsoft. The project was codenamed Harmony and it came to fruition in 2015, when ECMAScript 6 was released.

In 2009, the CommonJS project set out to define and promote JavaScript development outside the browser by using modules to package useful code and functionality.

This paved the way for Node.js as an environment to run browserless JavaScript. Now the language that ran the frontend of the internet was able to tackle the servers behind the scenes

Introduction

What is it?

A very small (~10k) open source JS library that can be used from asp.net (framework or core) to enhance web apps. It can also be used from other language such as PHP, python etc

By adding attributes to tags it will automatically wire up the calls to the server, parse the result and update the UI. Bit like AngularJS (maybe that’s why I like it) - but it’s not model binding it’s more like events and actions being bound to HTML elements.

Gets back to the basics / fundamentals of hypertext as Tim Berners Lee designed into the HTTP protocol back in the day.

What would you use it for?

What category of website is best suited? - SPA - Simple brochure-ware type site - Web app with security, authentication, roles etc?
- Any interaction with a server basically

Some examples of where it can be useful

  • Cascading selects
  • Typeahead
  • Filter lists
  • Infinite scrolling
  • Auto refresh - polling -
  • You could change a whole section of the page based on something the user selects (SPA style)

Lots of good examples on the website https://htmx.org/examples/

How would you use it?

Add via unpkg.com

<script src="<https://unpkg.com/[email protected]>" integrity="sha384-EzBXYPt0/T6gxNp0nuPtLkmRpmDBbjg6WmCUZRLXBBwYYmwAUxzlSGej0ARHX0Bo" crossorigin="anonymous" defer></script>

Attribute based - no javascript to write - BONUS! The HTML is server generated and then sent back to the client.

<button hx-post="/clicked"
    hx-trigger="click"
    hx-target="#parent-div"
    hx-swap="outerHTML"
>
    Click Me!
</button>

This tells htmx:

"When a user clicks on this button, issue an HTTP POST request to '/clicked' and use the content from the response to replace the element with the id ’parent-div’ in the DOM"

How flexible is it?

Htmx provides an extension mechanism for defining and using extensions within htmx-based applications.

Included Extensions

htmx includes a set of extensions out of the box that address common developer needs. These extensions are tested against htmx in each distribution

Defining an Extension

To define an extension you call the htmx.defineExtension() function:

<script>
  htmx.defineExtension('my-ext', {
    onEvent : function(name, evt) {
        console.log("Fired event: " + name, evt);
    }
  })
</script>

Typically, this is done in a stand-alone javascript file, rather than in an inline script tag.

Extensions should have names that are dash separated and that are reasonably short and descriptive.

 <script src="/path/to/ext/my-ext.js" defer></script>

<button hx-post="/example" hx-ext="my-ext">This Button Uses my-ext Extension</button>

Extensions can override the following default extension points to add or change functionality:

{
    onEvent : function(name, evt) {return true;},
    transformResponse : function(text, xhr, elt) {return text;},
    isInlineSwap : function(swapStyle) {return false;},
    handleSwap : function(swapStyle, target, fragment, settleInfo) {return false;},
    encodeParameters : function(xhr, parameters, elt) {return null;}
}

Finish up

Really simple way to make your site responsive/interactive without having to learn larger JS (ahem React (~100kb), Angular (566kb)) frameworks

OS project/utility of the week

https://day.js.org/

Fast 2kB alternative to Moment.js with the same modern API

Why Day.js?

2kB - Less JavaScript to download, parse and execute, leaving more time for your code.

Simple

Day.js is a minimalist JavaScript library that parses, validates, manipulates, and displays dates and times for modern browsers with a largely Moment.js-compatible API.

If you use Moment.js, you already know how to use Day.js.

Immutable

All API operations that change the Day.js object will return a new instance instead.

This helps prevent bugs and avoid long debugging sessions.

I18n

Day.js has great support for internationalization. But none of them will be included in your build unless you use them.