Fast & Agile YouTube Embed – Responsive iFrame load delay with jQuery

This code is an alternative to the traditional YouTube <iframe> embed. It will reduce the downloads of each embeded video by about 90% and have them resize responsively to all screen widths. It is made with jQuery, HTML, and CSS.

Great news! Eric Franklin has created a WP Plugin using my code and added Vimeo support.

Background

I noticed that YouTube <iframe> embeds are really slow. Upon investigation they are ~450kb for each embed. This is not the video, just the “ready to play” player. If you have a few videos on a page this could be loading a few mb of data for videos that never even get played.

The Solution

The idea is simple. Only load the screen shot of the video with a play button, then load the player only after it’s been clicked. This essentially reduces each instance from ~450kb to about ~30kb.

With a bit of research I found out I was not the only one with this idea. However, no one had put together a comprehensive solution that was up to the current coding standards and fully responsive. My version is based off of the code of Alexis Ulrich who had a pretty good version of this.

Working Example & Code

See the Pen Fast & Agile YouTube Embed by Jesse Schoberg (@schoberg) on CodePen.0

 Usage

  1. You must have jQuery running on your page. This can be done by including a single line of code that pulls from the Google CDN as shown here.
  2. Any spot you want to include a video simply put in the <div> as shown above on the HTML tab. Just set the id of the <div> to the ID of the video on YouTube.
  3. The first HTML example just shows the standard embed. If you’d like to get fancy and add some parameters, you can by adding them to the div’s data-params attribute as shown in the second example.
  4. Add the CSS shown to your style sheet.
  5. Add the javascript to your existing .js file, or directly into a <script> tag.

Notes