Load youtube player api asynchronously on jquery event - javascript

I need to load the youtube iframe player with api on a jquery change event but it only shows how to load it when the script is loaded.
This is the script they use to load the player with the api.
var tag = document.createElement('script');
tag.src = "//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: '390',
width: '640',
videoId: 'u1zgFlCw8Aw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
I need to wait to fire this until my change event is fired so inside this..
$(document).on("change","#yt-url", function() {
youtubeUrl = $(this).val();
youtubeId = youtube_parser(youtubeUrl);
// Load the youtube player with api
});
What's the correct way to do this?

I think you'd just need to encapsulate the code creating the player into a function, which is called only by given event
$(document).on("change","#yt-url", function() {
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
});

Dmitry's example works, but I've got two modifications. First, check to see if the API is already loaded (whether YT.Player is defined) and only load the API if it isn't. Second, you might as well use $.getScript() since you mentioned you're using jQuery.
There's an example of this approach at https://code.google.com/p/youtube-direct-lite/source/browse/static/js/ytdl/player.js

Related

Pass youtube iframe api events onstatechange when src changes

So I figured I would update this with a working example. I have ditched stating the iframe tag and just used the iframe api to create an iframe and then loaded the player by id with a data attribute. Here is a working example below. So now all statechanges are passed consistently through the youtube player. So the script will load an iframe into the Div #player and you can just loadVideoByID pretty easily with jquery and javascript.
<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
playerVars: { 'autoplay': 0,},
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
alert('started');
}
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
$( document ).on( "click", ".video-link", function(e) {
e.preventDefault();
var videoID = $(this).attr('data-videoID');
player.loadVideoById(videoID);
});
</script>
And then use a link with a data-attribute like so.
Link
Rather than having buttons to play, why not cue to playlist when the player is ready? You can hold the video ID's in an array... If this isn't what you're looking for just leave a comment below and I will change things the best I can to fit.
//Array of videos
var MyVideos=["E6RGMRamAFk","IHQr0HCIN2w","CogIXrea6A4"];
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
//Player is ready, cue the array of videos into the playlist.
player.cuePlaylist(MyVideos);
}
function onPlayerStateChange(event) {
}
JS Fiddle - Working Demo
YouTube JavaScript Player API Reference
If you have any questions please leave a comment below and I will get back to you as soon as possible.
I hope this help. Happy coding!

Does YouTube API not support looping in IE9?

So I'm sticking a background video into our webpage, and I have the following code:
function setupYoutubeBG(videoId){
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// , This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
window.onYouTubePlayerAPIReady = function() {
player = new YT.Player('bgPlayer', {
playerVars: { 'autoplay': 1, 'controls': 0,'autohide':1, 'wmode':'opaque', 'playlist':videoId, 'loop':1 },
videoId: videoId,
events: {
'onReady': onPlayerReady}
});
}
// The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.mute();
}
}
Which is pretty straightforward, pulled right from the documentation. Works fine in all browsers including IE11 but for some reason, when testing in IE9 the video doesn't loop. I've set the playlist to the videoId, and like I said, it works everywhere else. If anybody has an idea or can point me in the right direction, it would be appreciated.

Loading the youtube player API in Meteor

I understand how to load the Youtube IFrame player API normally in a document:
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
How would I do this in a meteor application though? I can't just put a <script> tag inside a template and I don't know if I can access document in one of the template helpers.
Is there some way to load it globally once the user connects for the first time?
there are several packages which can be used to use youtube iframe api
using the package adrianliaw:youtube-iframe-api we can do it like below
if (Meteor.isClient) {
onYouTubeIframeAPIReady = function () {
player = new YT.Player("player", {
height: "400",
width: "600",
videoId: "LdH1hSWGFGU",
events: {
onReady: function (event) {
event.target.playVideo();
}
}
});
};
YT.load();
}

Youtube Player won't start upon setTimeout, help needed

I have followed the Youtube API while constructing a player. I need to to call the autoplay function via javascript but it won't listen to the setTimeout function, and it won't start playing:
Could someone light me up where am I wrong?
Regards!
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: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
}
});
}
function onPlayerReady(event){
setTimeout(function(){
playVideo();
},5000);
}
As you are declaring player variable and later set it to instance of YT.Player, you have to use the same variable on setTimeout too.
setTimeout(function(){
player.playVideo();
},5000);

Youtube delay auto start video

There is anyway to delay the auto start of a youtube video for example:" 20seconds, after page loads?"
Here is the example just with the auto start:
http://jsfiddle.net/qbqEA/
Thanks
It is not perfect solution but it works,
<iframe class="delayed" width="486" height="273" frameborder="0" data-src="__url__" allowfullscreen=""></iframe>
note that I used data-src instead of 'src'
$(document).ready(function() {
setTimeout(function() {
$('iframe.delayed').attr('src',
$('iframe.delayed').attr('data-src'));
}, 20000);
}
It will load iframe 20 seconds after page loads.
see my fork: http://jsfiddle.net/WswGV/
The best way to do it is to use YouTube.API with Javascript functionality.
// Load the IFrame Player API code asynchronously.
setTimeout(function() {
player.playVideo();
}, 20000);
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '315',
width: '560',
videoId: 'I_V_kIzKKqM'
});
}
I hope this help
The link to the IFrame YouTube API above is obsolete, I think, but here's one I found today:
https://developers.google.com/youtube/iframe_api_reference
Wish I'd read that a long time ago.
To excerpt from the example there, I would suggest that you detect the player being downloaded and ready, then set a timer for the desired number of seconds (20 in your case, I think), and then play the video.
---v
Using https://developers.google.com/youtube/iframe_api_reference this will add a 10 second delay before the video automatically starts:
<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
setTimeout(function() {
event.target.playVideo();
}, 10000);
}
function stopVideo() {
player.stopVideo();
}
</script>
I use the following function
jQuery(document).ready(function () {
var frame = jQuery('.embed-responsive iframe');
var src = frame.attr('src');
setTimeout(function(){ frame.attr('src', src+'?autoplay=1'); }, 20000);
});

Categories