How to add external JS scripts to VueJS Components?

ghz 8months ago ⋅ 73 views

I've to use two external scripts for the payment gateways.

Right now both are put in the index.html file.

However, I don't want to load these files at the beginning itself.

The payment gateway is needed only in when user open a specific component (using router-view).

Is there anyway to achieve this?

Answers

Yes, you can dynamically load external scripts only when they are needed, such as when a specific component is loaded using the router-view. Here's how you can achieve this:

  1. Load External Scripts Dynamically: Instead of including the external scripts directly in the index.html file, you can dynamically load them when the specific component is mounted or when it's needed.

    For example, in your component's lifecycle hook (such as mounted), you can use JavaScript to dynamically create script elements and append them to the document's head:

    mounted() {
        const script1 = document.createElement('script');
        script1.src = 'url_of_external_script1';
        document.head.appendChild(script1);
    
        const script2 = document.createElement('script');
        script2.src = 'url_of_external_script2';
        document.head.appendChild(script2);
    }
    
  2. Lazy Loading with Vue Router: If you're using Vue Router, you can also leverage lazy loading to load components and their dependencies asynchronously when they are needed. This can be achieved using dynamic import.

    For example, in your router configuration:

    const PaymentComponent = () => import(/* webpackChunkName: "payment" */ './PaymentComponent.vue');
    
    const router = new VueRouter({
        routes: [
            {
                path: '/payment',
                component: PaymentComponent
            }
        ]
    });
    

    With dynamic import, the payment component and its dependencies will be loaded only when the /payment route is accessed.

By using one of these methods, you can defer the loading of external scripts until they are actually needed, reducing the initial load time of your application.