Search code examples
htmx

Measure request to response time with htmx


Using htmx, is there a way to measure the time it took to get a response from the server, starting from the time the request was sent?

My usage is that I have a user typing in a search bar, each new modification of the input text field (throttled at 50ms) triggers a new request to the server to fetch search results. The resulting HTML is then displayed on the page each time the server responds with some results. I would like to write some text with "387 results in 17ms".


Solution

  • The actual answer is to use the beforeRequest and afterRequest events to time it:

    <form hx-post=""
          hx-on::before-request="event.detail.xhr.go_time = performance.now()"
          hx-on::after-request="const elapsed = performance.now() - event.detail.xhr.go_time;
                                console.log(`That took ${elapsed} milliseconds.`);">