Skip to content

Orbulo/vue-plugin-load-script

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

30 Commits
 
 
 
 
 
 
 
 

Repository files navigation

vue-plugin-load-script license

A Vue 2 plugin for injecting remote scripts.

See the vue3 branch for Vue 3 support.

Compatible with Vue 3.

For Vue 2, see the master branch.

Install

# npm
npm install --save vue-plugin-load-script@">=2.0.0"
# yarn
yarn add vue-plugin-load-script@">=2.0.0"

Use

  // In main.js
  import { createApp } from "vue";
  import LoadScript from "vue-plugin-load-script";

  const app = createApp(App);
  app.use(LoadScript);

  app.mount("#app");
  // There are 2 ways of using the function:
  // By importing the function
  import { loadScript } from "vue-plugin-load-script";
  loadScript("https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY")
    .then(() => {
      // Script is loaded, do something
    })
    .catch(() => {
      // Failed to fetch script
    });

  // As an instance method inside a component
  this.$loadScript("https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY")
    .then(() => {
      // Script is loaded, do something
    })
    .catch(() => {
      // Failed to fetch script
    });

If you'd like to remove (unload) the script at any point, then call the companion method unloadScript / this.$unloadScript with the same URL.

  // There are 2 ways of using the function:
  // By importing the function
  import { unloadScript } from "vue-plugin-load-script";
  unloadScript("https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY")
    .then(() => {
      // Script was unloaded successfully
    })
    .catch(() => {
      // Script couldn't be found to unload; make sure it was loaded and that you passed the same URL
    });

  // As an instance method inside a component
  this.$unloadScript("https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY")
    .then(() => {
      // Script was unloaded successfully
    })
    .catch(() => {
      // Script couldn't be found to unload; make sure it was loaded and that you passed the same URL
    });

In most situations, you can just call unloadScript / this.$unloadScript and ignore the returned promise.

About

A Vue plugin for injecting remote scripts.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%