Loading External Scripts on Demand in Nuxt 3

Fayaz Ahmed

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).

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.

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
    }
  }
);