How to properly load Bootstrap5's Masonry into Nuxt?

Viewed 648
1 Answers

I checked how to load the script from a CDN either globally or locally. It was working but at one condition: you needed to NOT start on the masonry page.
Meaning that if you loaded the app on a specific page, then moved to the one with the masonry it was working. But not if you started on this specific page. So, a pretty subpar solution.

This article was really helpful to understand how to wait until the CDN script is fully loaded: https://vueschool.io/articles/vuejs-tutorials/how-to-load-third-party-scripts-in-nuxt-js/

Then I realized that we are far better installing it directly as an NPM dependency. Therefore, I proceeded to the masonry repo. Found a great message on how to setup the whole thing in Nuxt.

And after a removal of some useless stuff and some modern dynamic import, here we are

<template>
  <main>
    <h1>Bootstrap and Masonry</h1>

    <div class="row" id="masonry">
    <!-- ... -->
  </main>
</template>

<script>
export default {
  async mounted() {
    if (process.browser) {
      let { default: Masonry } = await import('masonry-layout')
      new Masonry('#masonry', { percentPosition: true })
    }
  },
}
</script>

The final solution is looking pretty well and there is not a lot of code. On top of that, the code is properly loaded. And you can load it on a click or any other event.

Related