javascripthtmlyoutube

How to know if the javascript youtube iframe api is being loaded


I am making a web application that uses the YouYube iframe API. However, I want it to be possible for my webapplication to be included in any webpage. This means that if the website already has the iframe API script loaded and already has a onYouTubeIframeAPIReady method implemented in global scope, that it should not load the script again (also, not overwrite onYouTubeIframeAPIReady ).

I suppose I could check if the YT.Player exists, but it may be the case that the Youtube API is not yet fully loaded, but is already in the process of being loading.

Currently I do:

var $youtubeApiScript.attr({
    'src': 'https://www.youtube.com/iframe_api'
});
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore( $youtubeApiScript[0], firstScriptTag ); 

However, I should first check if the website has that script already loaded or is already in the process of loading it.

How can we tell if the Youtube iframe API is already being loaded?


Solution

  • Still no official solution, but at the moment i came up with:

    if (typeof YT !== 'undefined' && YT.loaded) {
        //API is loaded
    }