Skip to content

Instantly share code, notes, and snippets.

@steelydylan
Created May 25, 2018 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steelydylan/ffd7855e7b68aa6982eb968ea30e78ed to your computer and use it in GitHub Desktop.
Save steelydylan/ffd7855e7b68aa6982eb968ea30e78ed to your computer and use it in GitHub Desktop.
jsonからランダムに動画を選んでdomに追加して再生するJavaScript
import randomVideo from 'random-video';
randomVideo('#js-random-video', '/sample.json');
import axios from 'axios';
const getRand = (a, b) => ~~(Math.random() * (b - a + 1)) + a;
export default (selector, url) => {
axios.get(url).then((item) => {
const data = item.data;
const index = getRand(0, data.length -1);
const target = data[index];
const poster = target.poster;
const source = target.source;
let html = `<video autoplay muted loop playsinline webkit-playsinline poster="${poster}">`;
source.forEach((src) => {
html += `<source src="${src}">`;
})
html += `</video>`;
document.querySelector(selector).innerHTML = html;
});
}
[
{
"poster": "/***/***.png",
"source": [
"/***/***.mp4",
"/***/***.webm"
]
},
{
"poster": "/***/***.png",
"source":[
"/***/***.mp4",
"/***/***.webm"
]
},
{
"poster": "/***/***.png",
"source":[
"/***/***.mp4",
"/***/***.webm"
]
}
]
@steelydylan
Copy link
Author

https://css-tricks.com/how-to-fix-video-slowing-down-page-load-time/

document.addEventListener('DOMContentLoaded',() => {
  randomVideo('#js-random-video', '/sample.json');
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment