Learn how to use the Youtube API and javascript to load only one video
The most common way to embed any video on Youtube is: Click in Share, Embed, copy the code and place in the website. I guess everybody used this at least once but let’s be realistic: This is not the best approach when you are working with clients as you never know what the client is going to ask in the future. It might happen the client will not request anything extra. Or he might ask to record the time the user paused the video.
My idea here is to make a very simple series of 4 articles which should cover the most basic usage of Youtube API. And they are:
- Load a single predefined video (this article)
- Load a custom video with the Youtube API in ASP.NET
- Create a video gallery with modal using ASP.NET and Bootstrap
For this series I am going to use the Youtube API for iframe embeds which forces the HTML5 player and it’s better for compatibility with mobile. You will find the code to download in the end of the article.
The player
When embedding a video we normally get a code like this:
<iframe width="560" height="315" src="https://www.youtube.com/embed/XdlmoLAbbiQ" frameborder="0" allowfullscreen><iframe>
However, since we are going to use the Youtube API, we will need a very simple code:
<div id="player"><div>
The Javascript
Here is where the magic happens. The javascript code will load the video we want and replace that div with the proper embed code. However, I will split this script in 2 parts.
General script
This script is used only to make the API calls. Note that we are using this approach since we still don’t have full support for async javascript calls straight from the script tag, so this script should take care of this for us. We need to call it just once.
Video Script
After setting the API call we need to load the video and the way we will do that is also through javascript. So far, in this example, all we will need is the video dimensions (height and width) and also the ID. We will set this up in the function onYouTubeIframeAPIReady(), which is executed once the API is ready to be used.
That’s it for now. In the next article I will show a very simple way to load a custom video. And for that I will use ASP.NET to simulate some database retrieval. But you can use your language/framework of choice.
Check the full code here: https://github.com/davidsonsousa/YoutubeAPI