I use angular route, and used the YouTube video API and wrote this code in a template (in the .html file). When I load the page, everything works fine, and when I switch between pages (without updating the page), this code just does not load and does not works. Did anyone have such a problem and how did you solve it?)
var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); // 3. This function creates an <iframe> (and YouTube player) // after the API code downloads. var player; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { height: '100%', width: '100%', videoId: '_fGbnVXMnHw', playerVars: { 'modestbranding': 1, 'showinfo': 0, 'iv_load_policy': 3, 'loop': 1, 'rel': 0 }, events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); } // 4. The API will call this function when the video player is ready. function onPlayerReady(event) { event.target.playVideo(); } // 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) { stopVideo(); done = true; } else if ( event.data == YT.PlayerState.PLAYING ) { $("#play-video").hide(); $("#player").removeClass("op_op"); } else if ( event.data == YT.PlayerState.PAUSED ) { } } var videos_btn = $("#play-video"); videos_btn.on("click", function(){ $("#player").removeClass("op_op"); videos_btn.off("click"); }); function stopVideo() { player.stopVideo(); } $("#play-video").click( function() { player.playVideo(); })