Home > Web Front-end > JS Tutorial > body text

How to Load External JS Scripts in VueJS Components on Demand?

Mary-Kate Olsen
Release: 2024-11-04 16:34:02
Original
533 people have browsed it

How to Load External JS Scripts in VueJS Components on Demand?

Loading External JS Scripts in VueJS Components on Demand

In Vue.js applications, you may encounter scenarios where specific components require external JavaScript scripts. By default, external scripts are added to the index.html file, which can lead to unnecessary loading when those scripts are not immediately needed.

To address this issue, Vue.js provides a convenient way to dynamically load external scripts within components, ensuring they are available only when necessary. This technique involves utilizing the mounted() lifecycle hook.

Solution:

The following code snippet demonstrates how to load an external script within a Vue.js component using the mounted() hook:

<code class="html"><template>
  ... your HTML
</template>

<script>
  export default {
    data: () => ({
      ... data for your component
    }),
    mounted() {
      let externalScript = document.createElement('script')
      externalScript.setAttribute('src', 'https://example.com/external-script.js')
      document.head.appendChild(externalScript)
    },
    methods: {
      ... methods for your component
    }
  }
</script></code>
Copy after login

Benefits:

  • Selective loading: External scripts are loaded only when the component is mounted, optimizing performance.
  • Modularity: Components can remain independent, as the external scripts are loaded separately.
  • Enhanced performance: By loading scripts on demand, you avoid unnecessarily bloating the page load time.

Example Source:

This solution was adapted from an article by Lassi Iso-Uosukainen: https://medium.com/@lassiuosukainen/how-to-include-a-script-tag-on-a-vue-component-fe10940af9e8

The above is the detailed content of How to Load External JS Scripts in VueJS Components on Demand?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template