Embed a YouTube player easily and lazy load the video to save resources and reduces initial load size. Useful when performance and page size is important or for sites with many embedded youtube videos.
For a simple example page with 10 videos, vue-lazytube will reduce loadtime by 7x and memory usage by 2-3x.
props
play
, stop
, pause
and reset
) embedded videosWith a build systems
$ npm install --save vue-lazytube
$ yarn add vue-lazytube
In your main.js
:
import LazyYoutube from "vue-lazytube";
Vue.component("LazyYoutube", LazyYoutube);
OR
To include only in specific components
import LazyYoutube from 'vue-lazytube'
export default {
name: 'YourComponent',
components: {
LazyYoutube,
},
}
OR
Directly in browser
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="./vue-lazytube.umd.min.js"></script>
<script>
// as a component
Vue.use('LazyYoutube', LazyYoutube)
</script>
HTML
<template>
<LazyYoutube src="https://www.youtube.com/watch?v=TcMBFSGVi1c" />
</template>
These methods let you control the player using JavaScript, so you can perform the operations like play
, stop
, pause
and reset
.
The user’s browser must support the HTML5 postMessage feature. Most modern browsers support postMessage.
<template>
<LazyYoutube
ref="lazyVideo"
src="https://www.youtube.com/watch?v=TcMBFSGVi1c"
/>
<button @click="handleClick('playVideo')">Play</button>
<button @click="handleClick('stopVideo')">Stop</button>
<button @click="handleClick('pauseVideo')">Pause</button>
<button @click="handleClick('resetView')">Reset</button>
</template>
<script>
export default {
name: "YourComponent",
components: {},
methods: {
handleClick(event) {
this.$refs["lazyVideo"][event]();
},
},
};
</script>
Author: seeratawan01
Live Demo: https://codesandbox.io/s/vue-lazytube-hj03y
GitHub: https://github.com/seeratawan01/vue-lazytube
#vue