Home >Web Front-end >JS Tutorial >How to Dynamically Include External JS Scripts in VueJS Components?

How to Dynamically Include External JS Scripts in VueJS Components?

Susan Sarandon
Susan SarandonOriginal
2024-11-04 22:37:01757browse

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:

  1. Create a script element and set its src attribute to point to the desired script file.
  2. Append the newly created script element to the document's section.

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:

  • [How to Include a Script Tag on a Vue Component](https://medium.com/@lassiuosukainen/how-to-include-a-script-tag-on-a-vue-component-fe10940af9e8)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn