·
1 min read

Nuxt Tip: Custom SPA Loading Template for Your Nuxt Application

MH

Michael Hoffmann

@mokkapps

Nuxt Tip: Custom SPA Loading Template for Your Nuxt Application Image

You can use Nuxt with the client-side rendering mode to create a single-page application (SPA). In this mode, Nuxt will only render the application on the client-side. This means that the server will only send a minimal HTML document to the client. The client will then render the application and fetch the data from the API.

When using the client-side rendering mode, Nuxt will display a loading indicator until the application is hydrated. The loading indicator is a simple spinner. You can customize the loading indicator by creating a custom loading component.

Since Nuxt 3.7 this loading indicator is disabled per default. You need to manually enable it by setting the spaLoadingTemplate option to true in your nuxt.config.ts file:
nuxt.config.ts
export default defineNuxtConfig({
  ssr: false, // enables SPA rendering mode
  spaLoadingTemplate: true, // per default disabled since Nuxt 3.7
})

You can place a custom HTML file in ~/app/spa-loading-template.html to customize the loading indicator. The file must contain a single HTML element which will be rendered as the loading indicator. For example, the following code is referenced in the official docs:

app/spa-loading-template.html
<!-- https://github.com/barelyhuman/snips/blob/dev/pages/css-loader.md -->
<div class="loader"></div>
<style>
  .loader {
    display: block;
    position: fixed;
    z-index: 1031;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 18px;
    height: 18px;
    box-sizing: border-box;
    border: solid 2px transparent;
    border-top-color: #000;
    border-left-color: #000;
    border-bottom-color: #efefef;
    border-right-color: #efefef;
    border-radius: 50%;
    -webkit-animation: loader 400ms linear infinite;
    animation: loader 400ms linear infinite;
  }

  \@-webkit-keyframes loader {
    0% {
      -webkit-transform: translate(-50%, -50%) rotate(0deg);
    }
    100% {
      -webkit-transform: translate(-50%, -50%) rotate(360deg);
    }
  }
  \@keyframes loader {
    0% {
      transform: translate(-50%, -50%) rotate(0deg);
    }
    100% {
      transform: translate(-50%, -50%) rotate(360deg);
    }
  }
</style>

StackBlitz

You can try it yourself in the following StackBlitz project:

If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :

I will never share any of your personal data. You can unsubscribe at any time.