Home > Article > Web Front-end > How to Dynamically Load External JS Scripts in Vue.js Components?
When working with payment gateways, integrating external scripts that facilitate the transactions becomes necessary. However, it is often undesirable to load these scripts at the initial page load. This is where Vue.js offers a solution for dynamically loading external scripts within specific components.
To achieve this, leverage the mounted() lifecycle hook in your Vue.js component. The mounted() hook executes after the component has been mounted and inserted into the DOM. This provides an ideal opportunity to conditionally load the external script.
Consider the following example, where we dynamically load the Google ReCaptcha script:
<code class="html"><template> ... your HTML </template> <script> export default { data: () => ({ ...data of your component }), mounted() { let recaptchaScript = document.createElement('script'); recaptchaScript.setAttribute('src', 'https://www.google.com/recaptcha/api.js'); document.head.appendChild(recaptchaScript); }, methods: { ...methods of your component }, }; </script></code>
By placing the external script loading logic in the mounted() hook, we ensure that the script is loaded only when the component is activated, thus preserving page performance and optimizing the user experience.
The above is the detailed content of How to Dynamically Load External JS Scripts in Vue.js Components?. For more information, please follow other related articles on the PHP Chinese website!