Integrate Aos animation library within nuxt

there is a long discussion on nuxt forum on how to properly integrate AOS animation library. The objective here for me is to experiment this light animation library without using npm with the aos nuxt module , instead i want to use CDN. This is quite straightforward with Nuxt and good alternative if you don't want to load the whole css / js into your compiled assets.

Integrate cdn in page head

The nuxt useHead composable function has script and stylesheet hooks, very useful when using composition API :

useHead({

  script: [

    {

      src: 'https://unpkg.com/aos@2.3.1/dist/aos.js',

      // valid options are: 'head' | 'bodyClose' | 'bodyOpen'

       tagPosition: 'bodyClose'

    },

  ],

  link: [

    {

      rel: 'stylesheet',

      href: 'https://unpkg.com/aos@2.3.1/dist/aos.css',

      crossorigin: ''

    }

  ]

})

As usual on most javascript libraries, you must instanciate the process , here we use aos.init with a few arguments of our choice

onMounted(() => AOS.init({

   once: false, // whether animation should happen only once - while scrolling down

  mirror: true, // whether elements should animate out while scrolling past them

}));

and that's it , we can use data-aos on our elements. Neat is it not ? problem now as discussed in the nuxt forum thread is that it won't reload on nuxtlink page change. as always, the solution is a mix of tips and trick founs on the internet

  • first import aos : pnpm install aos --save
  • then define your plugin :

import AOS from 'aos';
import 'aos/dist/aos.css';
export default defineNuxtPlugin((nuxtApp) => {
if (typeof window !== 'undefined') {
nuxtApp.AOS = AOS.init();
}
});

of course, you have noticed that the initial plan of manually integrating css and js from cdn is aborted, we now have no alternative but import aos from packages.

To top