Lazy-loading Embedded Videos

At MyEducator we do a lot of work with embedded, video content from our course creators.  As of the date of this article we use Vimeo Pro accounts which have worked well thus far, but we will probably migrate to something more commercial in the future.  Vimeo is not naturally supportive of business 🙂

A problem we ran into on a few courses was that we had too many videos embedded on the same page.  While the page loaded relatively quickly, when you tried to play a video it would delay for several minutes as all of the videos tried to load into the page.  That is just an unacceptable amount of wait time, so I came up with a straightforward way to lazy load the videos when they appear on screen.

Break the problem down into simple tasks:

  1. Check if “lazy content” is on screen
  2. Insert video code into page

For task 1 you can use a simple approach like Ben Pickles’ “onScreen” jquery plugin.  It is a simple, lightweight solution that works well.  We modified it slightly to check if an event is visible on the page (i.e. not visibility:hidden or display:none) before it evaluates as “onScreen”.

Task 2 is also very simple.  Start with dummy tags on the page like this:

<div class="lazy-video" data-vimeo-id="1"></div>

Then have some JavaScript find and replace it like so:

       var id = $(this).data('vimeo-id'),
           iframe = $('');
       iframe.attr('src', "" + id);
  }, 1000);

The idea is to check the page every second for videos that are “onScreen” and replace those elements with vimeo iframes. As a user scrolls through the page, more lazy-video divs get replaced by iframes and the list of divs to query gets shorter and shorter until only iframes remain.

This is not the exact code I used on the website, so you will have to do some modification to make it work how you want; but here is a working jsfiddle that gives you the core idea:

After implementing this feature, videos loaded near instantaneously. At the end of the day, you write code to fix problems and this solved a big problem for us! I hope this post helps you solve some problems to!

UPDATE – Dec 2013: We have since switched our lazy-loading system to a server-side function that creates the iFrame element, encodes it in Base64, and embeds it in an invisible div tag. When that div tag comes on screen, the Base64 is translated and the result replaces the invisible div tag.

Lazy-loading Embedded Videos