我试图通过api加载YT视频。当我将它直接输出到页面上时,这个官方教程片段基本上可以直接使用。当我尝试使用modules / webpack将其合并到我的JS工作流程中时,这是一个不同的故事。
问题:
如何在全局范围内使用这些方法(play / mute / setLoop / stop / etc)?
如何首先创建脚本标记,然后运行onYouTubeIframeAPIReady函数?
谢谢大家。希望这不是一个完全没用的问题!
<script>
// 1. Load up the script tag
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 2. Creates an <iframe> (and YouTube player) after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('a-spot-video-background', {
width: '1280',
height: '720',
videoId: 'T8v-gQeQZJY',
playerVars: {
autoplay: 1,
controls: 0,
modestbranding: 1,
rel: 0,
showinfo: 0,
loop: 1,
disablekb: 1,
color: 'white'
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 3. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.mute();
event.target.playVideo();
event.target.setLoop();
}
// 5. The API calls this function when the player's state changes. The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
//setTimeout(stopVideo, 10000);
player.playVideo();
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
答案 0 :(得分:0)
第一个问题在评论中得到回答。这回答了第二个问题:
function loadScript(scriptUrl, globalName) {
if (globalName && window[globalName])
return Promise.resolve();
return new Promise((resolve, reject) => {
let scr = document.createElement('script');
scr.type = "text/javascript";
scr.src = scriptUrl;
document.getElementsByTagName('head')[0].appendChild(scr);
scr.onload = (() => {
!globalName || window[globalName] ?
resolve() : reject(Error('window.' + globalName + ' undefined'));
});
scr.onerror = () => reject(Error('Error loading ' + globalName||scriptUrl));
});
}
var url = "https://code.jquery.com/jquery-3.3.1.min.js";
loadScript(url, "$")
.then(() => console.log('jQuery loaded. Now I can call any jQuery method.'));
或者你可以在没有承诺的情况下使用script.onload
事件监听器。我喜欢promise版本,因为它为您提供了一些额外的选项并且具有清晰的流程(没有嵌套或引用整个文件)。