Home >Web Front-end >JS Tutorial >How to Dynamically Include External JS Scripts in VueJS Components?
Including External JS Scripts in VueJS Components
Within a VueJS application, external scripts can be seamlessly integrated into specific components. This is particularly useful when scripts are intended to be loaded on an as-needed basis rather than at the application's initialization. For instance, a payment gateway script may only be required when a user navigates to a payment-related component.
Solution
To dynamically add external scripts to VueJS components, leverage the mounted() lifecycle hook. Within this hook:
Example
Consider a component that necessitates the Google Recaptcha script:
<code class="html"><template> ... your component's HTML </template> <script> export default { data() { return { ... your component's data }; }, mounted() { const recaptchaScript = document.createElement('script'); recaptchaScript.src = 'https://www.google.com/recaptcha/api.js'; document.head.appendChild(recaptchaScript); }, methods: { ... your component's methods } }; </script></code>
By utilizing this approach, the Recaptcha script will be dynamically loaded only when the component is rendered.
Additional Resource
For further insight into this technique, please refer to the following resource:
The above is the detailed content of How to Dynamically Include External JS Scripts in VueJS Components?. For more information, please follow other related articles on the PHP Chinese website!