Lightweight version check for web applications

Look mama, no build steps!
author's avatar
Kees de Kooter
Today 17:06

This code relies on the webserver generating etags that change if index.html changes. The application stores the original etag in localStorage on startup and subsequently starts polling that etag and comparing it with the stored version.

function verifyAppVersion() {
  fetch('/', {method: 'HEAD'}).then((response) => {
    window.localStorage.setItem('version-tag', response.headers['etag'])

    const timerId = setInterval(() => {
      fetch('/', {method: 'HEAD'}).then((response) => {
        if (
          response.headers['etag'] !==
          window.localStorage.getItem('version-tag')
        ) {
          // TODO: trigger event the application can respond to
          clearInterval(timerId)
        }
      })
    }, 120000)
  })
}