How can I load a 3rd party script widget?
The documentation I'm following says that I need to add the following code:
However I can't place a <script> tag inside a <template>. What should I do to load this widget?
2 Replies
Hi @NicolasPL. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
You are correct: in Nuxt (and Vue), you cannot place a
<script>
tag directly inside a <template>
. To load a third-party script widget like the Wompi checkout, you should use Nuxt's head management utilities to inject the script tag dynamically.
The recommended approach is to use the useHead
composable to add external scripts. For scripts that require custom attributes (like your data attributes), you can specify them in the useHead
configuration. However, note that not all custom data attributes are supported directly via the useHead
API, so you may need to use a combination of useHead
and DOM manipulation in a lifecycle hook.
Here’s how you can approach this:
1. Use useHead
to Load the Script
You can add the external script using useHead
in your <script setup>
block. For example:
This will load the script globally. However, to add all the required data-*
attributes, you need to create the script element manually and append it to your form after the component is mounted.
2. Dynamically Inject the Script with Data Attributes
You can use the onMounted
lifecycle hook to programmatically create and append the script tag with all the necessary attributes:
This approach ensures the script is only added on the client side, after the component is mounted, and all required attributes are set.
References
- How to add inline script tags to Nuxt 3?
- Nuxt SEO and Meta: useHead
If you need to manage many third-party scripts, consider using the Nuxt Scripts module for more advanced use cases and better performance management, as described in the Nuxt roadmap and community resources.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@230717673665724416> Kapa.ai is still learning and improving, please let me know how I did by reacting below.