yequari.com/content/notes/Implementing Status.Cafe Up...

2.1 KiB

title slug tags
Retrieving status.cafe Updates During Hugo Builds hugo-build-status-cafe
Hugo
Web Development

status.cafe provides you with a JavaScript snippet to include your status on your site. I don't update my status super often, so I don't need to be hitting m15o's servers on every page load. To get around this, I wanted to see if I could update my status as a build step in Hugo.

This is the script status.cafe provides:

document.writeln('<div id="statuscafe"><div id="statuscafe-username"></div><div id="statuscafe-content"></div></div>');
fetch("https://status.cafe/users/yequari/status.json")
  .then( r => r.json() )
  .then( r => {
    if (!r.content.length) {
      document.getElementById("statuscafe-content").innerHTML = "No status yet."
      return
    }
    document.getElementById("statuscafe-username").innerHTML = '<a href="https://status.cafe/users/yequari" target="_blank">' + r.author + '</a> ' + r.face + ' ' + r.timeAgo
    document.getElementById("statuscafe-content").innerHTML = r.content
  })

This takes just over a second to fully load. Fetching the above script takes 478ms, then running the script fetches a json file, which takes 680ms. Now this is asynchronous, which means a user is not waiting on this for the rest of the page to load, but it is noticeable that the status pops in later than everything else. The entire page loads in 1.22s

Here is the same functionality written as a hugo template

{{ $data := dict }}
{{ $url := "https://status.cafe/users/yequari/status.json" }}
{{ with resources.GetRemote $url }}
  {{ with .Err }}
    {{ errorf "%s" . }}
  {{ else }}
	<div id="statuscafe">
    {{ $data = .Content | transform.Unmarshal }}
    {{ $length := len $data.content }}
    {{ if eq $length 0 }}
        No status
    {{ else }}
    <div id="statuscafe-username">
    <a href="https://status.cafe/users/yequari" target="_blank">{{ $data.author }}</a> {{ $data.face }} {{ $data.timeAgo }}
    </div>
    <div id="statuscafe-content">
        {{ $data.content }}
    </div>
    {{ end }}
  {{ end }}
{{ else }}
  {{ errorf "Unable to get remote resource %q" $url }}
{{ end }}