A hard-working lazy YouTube plugin for Jekyll

[Tweet : nvALT]

All of the following code is collected in one Gist for reference.

I ended up going a little crazy with YouTube embeds on the site this week, and my load times suffered greatly. I had just added lazy loading for post images and seen some speed gains, but the Flash embeds were killing me. I needed the click-to-load feature that I’ve seen on other sites.

Here’s my solution. While I’m sure there are some perfectly good plugins available to do this, it had to start with markup, so wrote a tag plugin for Jekyll and worked from there.

The plugin is a modification of my earlier responsive YouTube plugin. Instead of inserting an object tag, it inserts a link element that I can style via CSS and hook via jQuery. It adds the needed information as data attributes on the tag, so parsing it later with jQuery is simple. Here’s the code, which can be easily modified to work with other services (for which I’d recommend creating separate Liquid tags).

Next I styled the element and added a few rules to prepare for the object embed to occur later. This is the compiled CSS, but the Compass/Sass version is available in the Gist as well.

Lastly, a quick jQuery script to handle the setup and replacement. This could be tied into a load-on-scroll plugin if you wanted to, but the performance gains were significant enough for my needs already. I have this compiled into my main JS file as part of a main object, but I made it standalone here. I think this should be working code…

To see it in action, visit any page on my site with a YouTube video.