Vue Plugin Load Script
vue-plugin-load-script is a Vue plugin designed for dynamically injecting and removing remote JavaScript files into a web application. It is fully compatible with Vue 3, with the current stable version being 2.1.1. For Vue 2 compatibility, users need to install version 1.x.x. The plugin offers both Composition API (`loadScript`, `unloadScript`) and Options API (`this.$loadScript`, `this.$unloadScript`) interfaces, providing flexibility for different project architectures. Its primary utility lies in integrating third-party SDKs or external libraries like Google Maps, Stripe.js, or analytics scripts that require dynamic loading after the initial application render. The project maintains an active status with updates typically tied to Vue major version releases or critical bug fixes, rather than a fixed release schedule. A key differentiator is its straightforward API for managing the lifecycle of external scripts within a Vue application.
Common errors
-
TypeError: app.use is not a function
cause Attempting to use `app.use` with a Vue 2 application setup while `vue-plugin-load-script` version 2+ is installed.fixFor Vue 2 projects, install `vue-plugin-load-script@^1.x.x`. For Vue 3, ensure you are creating your app with `createApp` from 'vue'. -
ReferenceError: loadScript is not defined
cause Using `loadScript` (Composition API style) without importing it as a named export from the package.fixAdd `import { loadScript } from 'vue-plugin-load-script';` to your script where `loadScript` is used. -
TypeError: this.$loadScript is not a function
cause Attempting to use `this.$loadScript` within a Vue 3 Composition API `setup()` function or outside of a component context where the plugin instance isn't available.fixWithin `setup()`, use the named import `loadScript`: `import { loadScript } from 'vue-plugin-load-script';` then call `loadScript(...)`. If in an Options API component, ensure the plugin is registered with `app.use(LoadScript)`. -
Error: Script couldn't be found to unload; make sure it was loaded and that you passed the same URL
cause The URL passed to `unloadScript` (or `this.$unloadScript`) does not exactly match a previously loaded script's URL.fixVerify the URL used for `unloadScript` is identical, including query parameters, to the URL used for `loadScript`. Store the URL in a constant to prevent inconsistencies.
Warnings
- breaking Version 2.x.x and above of `vue-plugin-load-script` are exclusively designed for Vue 3. Projects using Vue 2 must use version 1.x.x.
- gotcha When using `unloadScript` or `this.$unloadScript`, the URL passed must be an exact match (case-sensitive and including query parameters) to the URL originally used to load the script. Any deviation will prevent the script from being found and unloaded.
- gotcha Script loading failures can occur due to network issues, invalid URLs, CORS restrictions, or if the script itself encounters an error. The `loadScript` promise will reject in these scenarios.
- gotcha The `this.$loadScript` and `this.$unloadScript` methods are only available within the context of a Vue component using the Options API, or if the plugin is globally registered. They cannot be directly accessed in Vue 3's Composition API `setup()` function without explicitly using `getCurrentInstance()` and `proxy`.
Install
-
npm install vue-plugin-load-script -
yarn add vue-plugin-load-script -
pnpm add vue-plugin-load-script
Imports
- LoadScript
import { LoadScript } from 'vue-plugin-load-script';import LoadScript from 'vue-plugin-load-script';
- loadScript
import loadScript from 'vue-plugin-load-script';
import { loadScript } from 'vue-plugin-load-script'; - unloadScript
import unloadScript from 'vue-plugin-load-script';
import { unloadScript } from 'vue-plugin-load-script';
Quickstart
import { createApp, defineComponent, onMounted } from 'vue';
import LoadScript, { loadScript } from 'vue-plugin-load-script';
const RootComponent = defineComponent({
template: `
<div id="app">
<h1>Script Loader Example</h1>
<p>Check console for script load status.</p>
<div id="map" style="height: 300px; width: 100%;"></div>
</div>
`,
setup() {
// Replace with your actual Google Maps API key or use environment variable
const GOOGLE_MAPS_API_KEY = process.env.VUE_APP_GOOGLE_MAPS_API_KEY ?? 'YOUR_API_KEY_HERE';
const googleMapsUrl = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAPS_API_KEY}&callback=initMap`;
// Define a global callback function required by Google Maps API
(window as any).initMap = () => {
console.log('Google Maps API script loaded and initMap callback executed!');
// Example: Initialize a basic map
const mapElement = document.getElementById('map');
if (mapElement && (window as any).google?.maps?.Map) {
new (window as any).google.maps.Map(mapElement, {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
});
console.log('Google Map initialized.');
}
};
onMounted(async () => {
console.log('Attempting to load Google Maps script...');
try {
await loadScript(googleMapsUrl);
console.log('Google Maps script load promise resolved.');
// initMap will be called automatically by the Google Maps script once loaded
} catch (error) {
console.error('Failed to load Google Maps script:', error);
}
});
return {};
},
});
const app = createApp(RootComponent);
app.use(LoadScript); // Register the plugin globally for Options API access ($loadScript)
app.mount('#app');