0👍
Method 1 Using a plugin
First install vue-plugin-load-script via npm or yarn
npm install --save vue-plugin-load-script
In main.js add
import LoadScript from 'vue-plugin-load-script';
Vue.use(LoadScript);
Vue.loadScript(scriptUrl)
.then(() => {
// Script is loaded, do something
})
.catch(() => {
// Failed to fetch script
});
Thank you @halilcakar for mentioning this method. I didn’t know about this plugin until you showed it off.
Method 2 Implementing manually
mounted() {
//script already loaded exit
if (document.getElementById('external-source-script')) return;
//Create script tag
let script = document.createElement('script')
script.setAttribute('src', 'your-external-source') // <---------------
script.setAttribute('type', 'text/javascript')
script.setAttribute('id', 'external-source-script')
//Add external script dependency
document.head.appendChild(script)
}
beforeDestroy() {
//Remove the external source
let el = document.getElementById('external-source-script')
if (el) el.remove();
}
Source:stackexchange.com