将YouTube API回调函数放在DOMContentLoaded的回调中

问题描述 投票:0回答:1

我已经尝试使用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>
javascript html dom browser
1个回答
0
投票
https://www.youtube.com/iframe_api处的脚本期望onYouTubeIframeAPIReady是全局的。

如果不是,则超出范围。

© www.soinside.com 2019 - 2024. All rights reserved.