Perform Loading

For a request that takes a long time, it is advisable for the developer to provide feedback in the form of a loading message, which is a sign that the request is in progress and the user is expected to wait until it is completed. To handle this, Briz.js has events that will run before and after the request, which can be used to create loading during the request.

Example

<form data-ajax
  id="form"
  action="/example/loading"
  method="get"
>
  <button type="submit">Get Something</button>
</form>

<!-- spinner using tailwind -->
<div id="loading" class="flex justify-center items-center" hidden>
  <div class="animate-spin rounded-full h-12 w-12 border-t-4 border-b-4 border-blue-500"></div>
</div>

Then you need to create a separate JavaScript file, link it to the header, and mark it as type=“module.” This is where we write the event for the loading logic.

document.addEventListener("z:before-request", (event) => {
  const element = event.detail.request?.meta?.el
  if(!element) return
  
  if(element.id === "form") {
    const loading = document.querySelector("#loading")
    loading.hidden = false
  }
})

document.addEventListener("z:after-request", (event) => {
  const element = event.detail.request?.meta?.el
  if(!element) return
  
  if(element.id === "form") {
    const loading = document.querySelector("#loading")
    loading.hidden = true
  }
})

for the z:after-request event, element.id comes from the element that comes from the server, while z:before-request is the element.id that is on the client.

Demo


Go back