Blog of Raivo Laanemets

Stories about web development, consulting and personal computers.

KnockoutJS: show spinner while loading page

On 2016-03-17

KnockoutJS uses the page markup as a template. This makes some parts of if to show/flicker during page load before KnockoutJS binding are applied. There is a very simple way to show a CSS spinner instead and show the rendered view after the bindings are actually applied.

How it works

Page loading flow:

  • Browser loads page up to the spinner
  • Browser displays the spinner
  • Browser loads rest of page, including scripts
  • Part of page used for KnockoutJS template is not shown
  • Scripts load some data
  • KnockoutJS model is bound
  • View is rendered and the spinner is automatically hidden

Spinner is wrapped into conditional KnockoutJS tags. These tags have no effect until ko.applyBindings is called:

<!-- ko if: false -->
<div class="loader"></div>
<!-- /ko -->

Once ko.applyBindings is called, the conditional tags become active and the loader spinner element is removed from the page DOM by KnockoutJS.

Rest of the page is wrapped into element that has CSS property display: none set by a class hide. This hides the content until the class is removed:

<div data-bind="css: { hide: false }" class="hide">
  Message: <span data-bind="text: message"></span>
</div>

The class is automatically removed when bindings are applied by ko.applyBindings. This is achieved through the built-in css binding and the expression that always evaluates to false.

CSS spinner code was taken from http://projects.lukehaas.me/css-loaders/.