31 August 2016

A Better Method for Embedding YouTube Videos on your Website


It is easy to embed a YouTube video but you’ll be surprised to know how much extra weight that embedded YouTube video can add to your web pages. The browser has to download about half a Mb of extra JavaScript files (see screenshot) for rendering the YouTube video player alone. And these files are downloaded even if the visitor never plays the embedded video.

The embedded video not only increases the byte size of your web pages but the browser has to make multiple HTTP requests to render the video player. This increases the overall loading time of your page thus affecting the page speed score. The other drawback with the default YouTube embed code is that it isn’t responsive. If people view your website on a mobile phone, the video player may not resize properly for the small screen.

Embed YouTube Videos without Increasing Page Size

Google+ uses a clever technique for embedding YouTube videos – it just embeds the thumbnail image of a YouTube video and the actual video player is loaded only when the user manually clicks the thumbnail.

YouTube thumbnail images are about 15 kB in size so we are able to reduce the byte size of web pages by 500+ kb. That’s huge!

The video above is embedded using the same on-demand technique (demo).

When a visitor clicks the play button, the thumbnail image is replaced with the standard YouTube video player with autoplay set to 1 so the plays the video instantly. The advantage is that the extra YouTube JavaScript gets loaded only when someone decides to watch the embedded video and not otherwise.

Light and Responsive YouTube Embeds

The standard embed code for YouTube uses the IFRAME tag and the width and height of the video player are hard-coded thus making the player non-responsive.

The new on-demand embed code for YouTube is slightly different. You need not specify the player size as we are now embedding the video responsively. Also, the IFRAME is replaced with a DIV tag and the IFRAME is added to the page only when the visitor clicks the play button.

YouTube Embed Code

Embed YouTube Videos Responsively – Tutorial

Copy-paste the following snippet anywhere in your web page where you would like the YouTube video to appear. Remember to replace VIDEO_ID with the actual ID of the YouTube video.

<div class="youtube-player" data-id="VIDEO_ID"></div>

We will not assign height and width since the video player will automatically occupy the width of the parent while the height is auto-calculated. You can paste multiple DIV blocks with different video IDs if you need to embed multiple videos on the same page.

Next, place the JavaScript anywhere in your web template. It finds all embedded videos on a web page and then replaces the DIV elements with the video thumbnails.

<script>

    /* Light YouTube Embeds by @labnol */
    /* Web: http://ift.tt/2bGFoam */

    document.addEventListener("DOMContentLoaded",
        function() {
            var div, n,
                v = document.getElementsByClassName("youtube-player");
            for (n = 0; n < v.length; n++) {
                div = document.createElement("div");
                div.setAttribute("data-id", v[n].dataset.id);
                div.innerHTML = labnolThumb(v[n].dataset.id);
                div.onclick = labnolIframe;
                v[n].appendChild(div);
            }
        });

    function labnolThumb(id) {
        var thumb = '<img src="http://ift.tt/2bGFpex;,
            play = '<div class="play"></div>';
        return thumb.replace("ID", id) + play;
    }

    function labnolIframe() {
        var iframe = document.createElement("iframe");
        var embed = "https://www.youtube.com/embed/ID?autoplay=1";
        iframe.setAttribute("src", embed.replace("ID", this.dataset.id);
        iframe.setAttribute("frameborder", "0");
        iframe.setAttribute("allowfullscreen", "1");
        this.parentNode.replaceChild(iframe, this);
    }

</script>

Finally, paste the CSS before the closing head tag of your web template.

This method will reduce the size of your web pages by 500 KB while making your site mobile friendly. You may refer to the annotated code to understanding how on-demand embedding works.

<style>
    .youtube-player {
        position: relative;
        padding-bottom: 56.23%;
        /* Use 75% for 4:3 videos */
        height: 0;
        overflow: hidden;
        max-width: 100%;
        background: #000;
        margin: 5px;
    }
    
    .youtube-player iframe {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 100;
        background: transparent;
    }
    
    .youtube-player img {
        bottom: 0;
        display: block;
        left: 0;
        margin: auto;
        max-width: 100%;
        width: 100%;
        position: absolute;
        right: 0;
        top: 0;
        border: none;
        height: auto;
        cursor: pointer;
        -webkit-transition: .4s all;
        -moz-transition: .4s all;
        transition: .4s all;
    }
    
    .youtube-player img:hover {
        -webkit-filter: brightness(75%);
    }
    
    .youtube-player .play {
        height: 72px;
        width: 72px;
        left: 50%;
        top: 50%;
        margin-left: -36px;
        margin-top: -36px;
        position: absolute;
        background: url("//i.imgur.com/TxzC70f.png") no-repeat;
        cursor: pointer;
    }

</style>

Please do note that Chrome and Safari browsers on iPhone and Android only allow playback of HTML5 video when initiated by a user interaction. They block embedded media from automatic playback to prevent unsolicited downloads over cellular networks.

YouTube Embed Tutorials

  1. Embed a YouTube Video with Sound Muted
  2. Place YouTube Video as your Webpage Background
  3. Embed Just a Portion of a YouTube Video

The story, A Better Method for Embedding YouTube Videos on your Website, was originally published at Digital Inspiration by Amit Agarwal on 31/08/2016 under Embed, YouTube, Internet.

No comments:

Post a Comment