javascript - YouTube API 回调函数在将它们放入 DOMContentLoaded 的回调中时不可用
问题描述
我尝试使用 Youtube API,但它不起作用,因为它的回调函数在将它们放在 DOMContentLoaded 的回调中时不可用,我寻求对此行为的详细解释。
// main.js
document.addEventListener("DOMContentLoaded", function () {
const tag = document.createElement('script');
const firstScriptTag = document.getElementsByTagName('script')[0];
const recordButton = document.getElementById("btn-record");
const recordedChunks = [];
let youtubePlayer;
// Setup YouTube API
tag.src = "https://www.youtube.com/iframe_api";
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// This function creates an <iframe> (and YouTube player)
// after the API code downloads.
function onYouTubeIframeAPIReady() {
youtubePlayer = new YT.Player('yt-player', {
height: '390',
width: '640',
videoId: 'g2MKmLiT7sw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// rest of js code...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>YT - Karaoke</title>
</head>
<body>
<div id="yt-player"></div>
<button id="btn-record"></button>
<p class="err"></p>
<audio id="player" src="" controls></audio>
<script src="main.js"></script>
</body>
</html>
解决方案
https://www.youtube.com/iframe_api上的脚本期望 onYouTubeIframeAPIReady 是一个全球性的。
如果不是,则超出范围。
推荐阅读
- javascript - 检查字段是否已使用 Angular 6 和 Firestore 进行了修改
- kubernetes - 应为 Kubernetes AWS 中的 Traefik 提供哪个主机 URL?
- python - 无法将 scipy 添加到 pycharm
- git - 当未检测到更改时,Git 将现有的本地存储库推送到新的远程分支
- signalr - 核心 2.1 SignalR 和 SQLDependency
- html - 在缩放时居中英雄图像
- javascript - 网站在单个窗口中打开
- python - 复制数据框单元格并附加到所有行中数据框末尾的新列
- angular - Angular - 重新启动 CSS 动画
- magento - Magento 1.9 面包屑总是空的