Nuxt·

Loading External Scripts on Demand in Nuxt 3

Learn how to load external scripts on demand in Nuxt 3 using the useScript composable.
Post image

I wanted to load a script based on a query parameter, Nuxt now had an official useScript() composable. It's really powerful, but I wanted to do something a bit different, which I couldn't find an example of anywhere (it's pretty new).

Nuxt Script module

The new Nuxt Script module is quite powerful but I feel their docs could be improved, I was trying to figure out how to load a script on demand for a while and in the end Harlan Wilton just helped me out directly.

My use case

I use lemonsqueezy for affiliate tracking, and they have a script I need to load if a user is referred from an affiliate. Turns out there's a trigger: manual option in the composable, which is exactly what I needed.

Here's how I am managing to load the script only when needed.

Example

app.vue
<script setup lang="ts">
const route = useRoute();
const script = useScript('https://lmsqueezy.com/affiliate.js', {
  trigger: 'manual',
  beforeInit() {
    if (import.meta.client) {
      window.lemonSqueezyAffiliateConfig = {
        store: 'supersaas',
        trackOnLoad: false,
        onReady(e) {
          e.Track(route.query.affiliateId);
        },
      };
    }
  },
});
watch(
  () => route.query.affiliateId,
  (val) => {
    if (val) {
      script.load();
    } else {
      // TODO reset the affiliate id if needed
    }
  }
);
</script>