I debugged the problem. onYouTubeIframeAPIReady () is only called the first time the YouTube API is loaded (when the user refreshes the page and clicks the link to the view, for example), and because I call my views in Ajax, this did not work at the following times.
So, I replaced the first block of code by wrapping it in a conditional expression:
if (typeof youtube_api_init == 'undefined') { var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); }
and
if (typeof youtube_api_init != 'undefined') { onYouTubeIframeAPIReady(); }
and at the end of the script, I set youtube_api_init for the browser to remember that the YouTube API is already loaded:
var youtube_api_init = 1;
PS: the first time I tried, I named my variable yt_api_init instead of youtube_api_init, and it didn’t work because it happens that the name YouTube already uses in its api ...
source share