Skip to content

Instantly share code, notes, and snippets.

@jam2-hey
Last active June 29, 2019 06:25
Show Gist options
  • Save jam2-hey/8990c0641175561b2d3dd016133e4260 to your computer and use it in GitHub Desktop.
Save jam2-hey/8990c0641175561b2d3dd016133e4260 to your computer and use it in GitHub Desktop.
Initialize Youtube iFrame API

Youtube iFrame Player API - Vue Plugin

A Vue.js Plugin that initializing Youtube iFrame Player API for you.

Example

// In main.js

import YoutubePlayerAPI from './lib/vue.plugin.youtube-player.js'

Vue.use(YoutubePlayerAPI);

// In component
<template>
  <div class="video-stage">
    <div ref="player"></div>
  </div>
</template>

<script>
export default {
  mounted () {
    this.$requireYoutubeAPI()
      .then(() => {
        // Youtube API is ready to use here.
        this.player = new window.YT.Player(this.$refs.player, {
          height: '390',
          width: '640',
          videoId: 'dQw4w9WgXcQ'
        });
      });
  }
};
</script>
export default {
currentPromise: null,
isLoaded: false,
install (Vue, options) {
Vue.prototype.$requireYoutubeAPI = () => {
if (this.isLoaded) {
return Promise.resolve();
}
if (this.currentPromise) {
return new Promise((resolve, reject) => {
this.currentPromise.then(() => resolve());
});
}
this.currentPromise = this.loadYoutubeAPI();
return this.currentPromise;
};
},
loadYoutubeAPI () {
return new Promise((resolve, reject) => {
const scriptLoader = document.createElement('script');
const firstScriptElement = document.getElementsByTagName('script')[0];
scriptLoader.src = 'https://www.youtube.com/iframe_api';
firstScriptElement.parentNode.insertBefore(scriptLoader, firstScriptElement);
window.onYouTubeIframeAPIReady = () => {
resolve();
this.isLoaded = true;
this.currentPromise = null;
};
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment