Michal Politzer
Michal Politzer

Reputation: 313

Embeded Youtubu doesn't load on mobile safari, when hidden

Google changed something last days, so I have strange problem with Youtube embeded as iFrame in mobile safari. When iFrame is hidden (some parent div has set display:none) during page load and later is changed to be visible, Youtube player do not play.

Any solution? I've tried to reload iframe, when it turns to visible state, it works. But it is not comfortable solution…

Upvotes: 0

Views: 379

Answers (1)

recneps
recneps

Reputation: 1295

I am assuming you are using the third party youtube Iframe API to load the youtube player into a div. The code from youtube actually has a race condition in it where if the div is not loaded/ parsed by the browser prior to onYouTubeIframeAPIReady being called, the video load will fail. In firefox it will just hang and for a second and Chrome is smart enough to deal with the problem.

The solution is to make sure that this code. Is run after the container holding the video is parsed.

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 this code...

function onYouTubeIframeAPIReady() {

Has global scope and is called after the script is created.

The way I typically solve this to to create a function 'class' with the tag creator and event listener and create the object in my document.ready function. Then right below the document.ready function I put.

function onYouTubeIframeAPIReady() {
    myVideo.apiReady();
}

Where 'myVideo' is the class I have create and apiReady(); contains.

this.apiReady = function () {
    player = new YT.Player('player', {
        height: '548',
        width: '900',
        videoId: 'VIDEO234324',
        events: {
            'onReady': onPlayerReady
        }
    });
}

I hope this helps.

Upvotes: 1

Related Questions