jQuery Plugin To Embed Youtube Videos Smartly

When you embed YouTube videos in your webpages make your webpages very heavy. Additional JavaScript files required for YouTube player are to be downloaded by your browser. This additional burden makes your webpage heavy to load, which might affect your website’s load speed.

Better Way of Embedding YouTube Videos

If you want to embed YouTube videos in your webpage and don’t want to compromise with the load speed, here is a quick solution for you.

  • Display thumbnail of your video, with a play button at the center of image.
  • When user clicks on this play button, dynamically add YouTube player in place of the thumbnail image.

This is a two step solution, which seems pretty easy to implement.

Advantages of this approach

  • Page load light as only a thumbnail image is fetched on page load.
  • All the additional JavaScript files are fetched on demand basis.

Even though the solution is pretty easy to implement, but it requires understanding of JavaScript to do so. So, in this tutorial we will create a jQuery plugin that will allow us to emebed YouTube videos in a better way.

jQuery Plugin For Embedding YouTube Videos

 

$(function() {

  $.fn.youtubeEmbed = function(options) {

    if((typeof options == "undefined" || typeof options.youtubeID == "undefined") && 
      typeof $(this).attr("data-youtube-id") == "undefined")
        throw new Error("Youtube video ID not provided");
    else {
      var youtubeVideoId = typeof options != "undefined" && options.youtubeID ? options.youtubeID : $(this).attr("data-youtube-id");

      var currentObject = $(this);

      var youtubeImageObject = '<img src="https://i.ytimg.com/vi/ID/hqdefault.jpg"><div class="play"></div>';

      currentObject.append(youtubeImageObject.replace("ID", youtubeVideoId));

      currentObject.find(".play").click(function() {
        var iframe = document.createElement("iframe");
        var embed = "https://www.youtube.com/embed/ID?autoplay=1";
        iframe.setAttribute("src", embed.replace("ID", youtubeVideoId));
        iframe.setAttribute("frameborder", "0");
        iframe.setAttribute("allowfullscreen", "1");
        currentObject.html(iframe);
      });
  }
};

$("#youtubeContainer").youtubeEmbed();

});

Leave a Reply

Your email address will not be published. Required fields are marked *