DEV Community

Cover image for Lazy load components in Nuxt to improve performance
Jakub Andrzejewski
Jakub Andrzejewski

Posted on

Lazy load components in Nuxt to improve performance

When working with Web Performance, I always liked solutions that based on one of my favourite concepts -> Lazy Loading. So, when I heard that one of the core features of Nuxt is Lazy Loading components, I thought that I need to try it out.

Long story short, the result is amazing so I decided to write a short blog post about it get you familiar with it.

Enjoy!

πŸ€” What is lazy loading?

One of my all time favorite pattern for improving performance in modern web applications is relatively simple to explain:

Just load what the user actually needs
Enter fullscreen mode Exit fullscreen mode

This sounds really easy right? It should be, but believe me, with modern frameworks and with the pace of development we usually forget about this pattern and we put everything inside our application, and eventually for our users.

This results in huge code bundles, megabytes of data transfer for the users, and bad performance.

And the medicine is in the reach of our hands. When a user don't need it, just defer the loading of it until the time that it will be.

If you are interested in learning more about lazy loading, check out my previous article about it here

🟒 Lazy Loading components in Nuxt

The components in Nuxt can be easily lazy loaded (in other words imported dynamically) by adding just a single keyword to the component name -> Lazy

<template>
  <LazyTheFooter />
</template>
Enter fullscreen mode Exit fullscreen mode

This lazy loading can be triggered also by an event like click like so:

<script setup lang="ts">
const isLazyLoadedComponentVisible = ref(false)
</script>

<template>
  <div>
    <button @click="isLazyLoadedComponentVisible = true">Load component</button>
    <LazyTheFooter v-if="isLazyLoadedComponentVisible" />
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

This is not only a trick but it actually makes the request for the component while it is actually needed fetching the code in the network tab after the event has been triggered.

πŸ“– Learn more

If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this link or by clicking the image below:

Vue School Link

It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects πŸ˜‰

βœ… Summary

Well done! You have just learned how to utilize lazy loaded components to improve performance of your Nuxt app and decrease the JavaScript bundle.

Take care and see you next time!

And happy coding as always πŸ–₯️

Top comments (0)