LazyYT.js: A jQuery plugin to lazy load Youtube videos
At New Media Campaigns, we take page load speed serious with all the sites we build. Unfortunately, even if we follow all the best practices for a quick-loading website, the 3rd-party code required for widgets like social media share buttons or video embeds for Youtube can still drastically slow down a site.
On a site we were coding this week, Youtube video embeds were causing an obnoxious lag on every page load. In order to speed things up, we wrote a jQuery plugin called lazyYT.js. While we have done similar custom setups for sites we have built before, we wanted to put together something simple, easy-to-use, and available for anyone.
To speed up the page load LazyYT works by initially loading a preview image, then waiting until the video is actually clicked to load and start the full Youtube video.
lazyYT.jsafter the jQuery library.
Use the following html wherever you would normally be embedding the
iframesnippet Youtube provides.
<div class="js-lazyYT" data-youtube-id="IcWJ79yUy3U" data-width="300" data-height="200"></div>
There are 3 required data attributes:
- youtube-id for the id of the Youtube video
- width for the width of the video
- height for the (you guessed it!) height of the video
Run the plugin, most likely within a DOM ready function.
- Check out your website and make sure everything is working properly.
- Prepare yourself for all the thank you emails from visitors commenting on how fast the site loads now.
If you have any suggestions for improvements, please feel free to shoot us a message or add a comment below.