Blog

Where we discuss our work, thoughts, and process

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.

Setup

  1. Include lazyYT.js after the jQuery library.

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" src="/path/to/js/lazyYT.js"></script>
    
  2. Use the following html wherever you would normally be embedding the iframe snippet Youtube provides.

    <div class="js-lazyYT" data-youtube-id="IcWJ79yUy3U" data-width="300" data-height="200"></div>

    There are 3 required data attributes:

    1. youtube-id for the id of the Youtube video
    2. width for the width of the video
    3. height for the (you guessed it!) height of the video
  3. Run the plugin, most likely within a DOM ready function.

    $('.js-lazyYT').lazyYT(); 
  4. Check out your website and make sure everything is working properly.
  5. Prepare yourself for all the thank you emails from visitors commenting on how fast the site loads now.

Demo

View the demo

Download

Download from Github

 

Feedback

If you have any suggestions for improvements, please feel free to shoot us a message or add a comment below.

Comments

Seven Kader's avatar
Seven Kader
Can you help me set this up? I don't have enough knowledge to do so alone :(
Dennis's avatar
Dennis
Thank you for the great work and for sharing it under a permissive license!
Tyler Pearson's avatar
Tyler Pearson NMC team member
@Dennis: No problem! Glad you found it useful.
wil's avatar
wil
Thanks for this useful tool. Do you guys also use this on responsive designs where the height and width is always in flux?
Luke Robinson's avatar
Luke Robinson
Thank you! Your script makes a huge difference when building mobile-first websites.

A tip to share that my co-worker (Ryan) discovered: changing the source of YouTube's thumbnail image from "0.jpg" to "maxresdefault.jpg" vastly improves image quality*.

The "maxresdefault.jpg" is true to widescreen video previews (16:9) without resorting to TV's traditional letter-boxing (black bars top and bottom).

*Of course, a thumbnail's quality depends upon its video quality.

Cheers!
Andy Findlay's avatar
Andy Findlay
Thanks for the excellent tut, Tyler. I'm not a programmer and this took me about 20 minutes to work through and install, so I'm very happy. Thank you!

I tried to implement some of the other youtube parameters into the js file, but could not get them to work. I'd like to add the following which works in an iframe:

showinfo=0&iv_load_policy=3&modestbranding=1&nologo=1&vq=large&autoplay=0&ps=docs

Can you help on how I would do this?
Thanks again
Andy
Tyler Pearson's avatar
Tyler Pearson NMC team member
@Luke: Thanks for the heads up! I wasn't aware of the other option. I just pushed an update to Github that has this change.

@Andy: Just shot you an email about this question -- currently it doesn't the option to pass parameters to the iframe URL. It definitely makes sense to have this functionality though, so I'll update the plugin.
Luke Robinson's avatar
Luke Robinson
@Tyler: You're welcome; lazyYT is a great.

There's a conversation on StackOverflow titled, "How to get thumbnail of YouTube video link using YouTube API?", with specifics all the thumbnails sizes provided by YouTube.

YouTube's default thumbnails include: maxresdefault, hqdefault, mqdefault.jpg, and default.jpg.

http://stackoverflow.com/questions/2068344/how-to-get-thumbnail-of-youtube-video-link-using-youtube-api
Andy Findlay's avatar
Andy Findlay
Hello Tyler,
I was able to add these parameters by updating the .js file as follows:



Users can add their own parameters as defined by YouTube
https://developers.google.com/youtube/player_parameters
Pretty simple even for a village idiot like me.
Cheers!
Sara's avatar
Sara
Any way to get the video to play in iOS without clicking twice?

-Sara
Tyler Pearson's avatar
Tyler Pearson NMC team member
@Sara: Apple prohibits video elements from autoplaying, which is causing the double click issue on iOS. Unfortunately since the plugin works by swapping the image with an autoplaying video on click/touch, I don't think there is currently a way around what you mentioned.
Will's avatar
Will
Could this or a variation work with Vimeo videos?
Riad Supriadin's avatar
Riad Supriadin
Great work but the Demo page not found.
Tyler Pearson's avatar
Tyler Pearson NMC team member
@Riad: Thanks for pointing that out -- it must have broken with the switch to our new site. I'll update it.
Christian's avatar
Christian
Thank you very much for this great idea!
As you may have noticed, Im using a lot of embedded YouTube videos directly on my front page. The problem is, I don't know how to implement JavaScript on Wordpress based homepages. Could you maybe help me out? Im sure the result would be awesome, especially on my site.

cheers Chris
Victor's avatar
Victor
I managed to get your plugin working, and for the most part absolutely love it! I'm having one slight issue though, that if someone could help me figure out it would be greatly appreciated.

For some reason I'm not sure of, certain videos just have a light-gray background image with a dark gray shape in the center and a few dots. (I'm guessing some kind of youtube loading graphic). This isn't for every video though, some perform beautifully and have a fantastic image from the video. I can't figure out why some videos work, and some don't. Thanks to all who can help!
andrei's avatar
andrei
Hello

Nice plugin. After a few tries, I've managed to get it working. By thw way, if someone is having troubles with youtube thumbnails, use mqdefault.jpg instead of maxresdefault.jpg, especially in the case of older videos. But there is a problem: responsive web design. ;) This plugin can be adjusted to work on responsive sites? Otherwise, as nice as it is, it's beyond these times.
Alejandro's avatar
Alejandro
Very nice plugin.
Many thumbnails didn't work till I replaced 'background': 'url(http://img.youtube.com/vi/' id '/maxresdefault.jpg) with 'url(http://img.youtube.com/vi/' id '/0.jpg). Line 24.

@Victor, hope this is useful.
tim99's avatar
tim99
thx very much! used it on my dogs page (prinzessin-sally.de)

but i had to too also -Alejandro-'s change: "Many thumbnails didn't work till I replaced 'background': 'url(http://img.youtube.com/vi/' id '/maxresdefault.jpg) with 'url(http://img.youtube.com/vi/' id '/0.jpg). Line 24. "

thx very much to both of you! :)
Tyler Pearson's avatar
Tyler Pearson NMC team member
Thanks for the heads up on the preview image! Just pushed an update.
Ryan's avatar
Ryan
Hi -- can you tell me which browsers/versions this is supported in? I tried IE 8 (standards mode) and the video doesn't render... all other browsers seem to work well...

Thanks!
Marcus's avatar
Marcus
Nice plugin!
Has anyone figured out how to make it available in feeds? Most rss clients understand javascript but since xml is for data only i’m wondering how one would tackle this one.
Ignacio's avatar
Ignacio
Hi Tyler,
Do you know any SEO issue using this method?
Will Google (and other robots) know that there's a youtube video in the content ?

Thank you
Luís Dias's avatar
Luís Dias
Great plugin and really useful! Thanks for sharing it under MIT.

Luís
Chris Mullins's avatar
Chris Mullins
Hi

Brilliant script, exactly what i was looking for.

Having some trouble with using this in Zurb Foundation's reveal modals, all works well placing the lazy load iframe into the modal with the user being able to open the modal then click the image and have the video start playing, however after the user exits the modal the video will stop playing and disappear but then starts playing in the background somewhere. Is there any way to prevent this? any help would be appreciated. Cheers
John Pullam's avatar
John Pullam
I have successfully installed this and used it in a normal web page as described and it works great. The plugin is in a link like this:

and I called it in the ready event like this:
$("document").ready(function() {
$('.js-lazyYT').lazyYT();

But I can't get it to work inside a module that I have loaded dynamically with a jquery .load

This may be more of a javascript or jquery question, but what do I need to do to make it work when the code is dynamically loaded? I can make the space for the image, but it doesn't seem to execute.
Daniel's avatar
Daniel
Just an FYI that your demo link is broken now.
Nathan's avatar
Nathan NMC team member
@Daniel Fixed! Thanks.
Fred Flintstoned's avatar
Fred Flintstoned
Would the use of this plugin affect Youtube Analytics?
For example, if a video is loaded using Lazy-YT, would it count as a view even though the user does not click on the play button on the video?
Angus Paterson's avatar
Angus Paterson
Hi Tyler,

Brill Scripting script! Thanks for the hard work.

I just wondered if you'd be able to tell me where to add the ‘&rel=0‘ to prevent related videos displaying at the end of each video.

Thanks so much.

Angus
Rut Scarborough's avatar
Rut Scarborough
Angus, This worked for me.
loading...
Rut Scarborough's avatar
Rut Scarborough
Angus,
Sorry the code did come through:
Let's try this:
div class="lazyYT" data-youtube-id="_oEA18Y8gM0" data-parameters="rel=0">loading...</div
David's avatar
David
Hi,

Nice work on the plugin, really useful. As mentioned by others previously, I am also having issues with Foundation starting videos again when a modal window has been closed. However I'm not sure if this is something that should be addressed through LazyYT or through Foundation itself? Any ideas?

Many thanks,
David
Luc's avatar
Luc
Hi Tyler,

I noticed that lately the titles of the youtube video's aren't displayed anymore. Instead it gives a standard "https://youtube.com/devicesupport" title.
See it also on your demos.
Any ideas on how to fix that?
Thx for your great coding. I use it with pleasure!

Best regards,
Luc.
Peter's avatar
Peter
Is it possible to start with thumbnails when the page loads (ie. like in your grid.html demo) and, when the user clicks a video's play button, a larger version of the video pops up on top and plays?
lirona's avatar
lirona
Hi
as you can see in the URL i used your plug and its great i just have 1 problem i cant see the front image
what do i need to do for that to work?
thanks!!
redd's avatar
redd
hi is there any way to get the current time of the video if the user clicked it to pause ?

like
$(".js-lazyYT").click(function(){
if( $(this).(":isPaused") ) {
var time = $(this).getCurrentTime();
}
});

?
Peter Verkooijen's avatar
Peter Verkooijen
Would it be possible to write a php script/function/filter/parser (?) that converts a standard youtube iframe tag to the alternative div replacement?

Manually replacing all iframes is not really an option for my site. It also makes it a lot harder to revert back if the plugin breaks for whatever reason, if youtube makes incompatible changes, etc.
Peter Verkooijen's avatar
Peter Verkooijen
...or make the jquery script read the standard iframe tag, get the required data attributes from there and output it in a div?

I can try to figure that out with my limited php/jquery skills, but would it even be possible? It would make the plugin so much easier and safer to implement.
Peter Verkooijen's avatar
Peter Verkooijen
...and this approach seems similar to yours, but the change to the iframe tag is less dramatic/intrusive and maybe easier to achieve "programmatically"?

https://varvy.com/pagespeed/defer-videos.html
naveen reddy's avatar
naveen reddy
HI Team,
i have faced small issue in this plugin..i used this plugin in my website::"http://www.edfenergy.com/zingy-as-seen-on-edf-energy-adverts", when you open this URL got the "loading..." text instead of title of the video,can you please guide me overcome the loading... text.
Mark Rossiter's avatar
Mark Rossiter
Hey Peter Verkooijen,

I currently use that Varvy.com script on a few sites I've made (www.emeraldzone.net for example). I find it better overall as it's really simple and effective, however does not work great in IE - just a head's up!

Cheers,
Mark
Wim Huiskes's avatar
Wim Huiskes
Pause button is missing. Also in the demo site, how can we resolve this?
Tim's avatar
Tim
Hi Tyler,
Your script demo looks awesome, and is exactly what I need, unfortunately I cannot get it to work because the instructions get a little vague for non-coders..
Please can you clarify item 6

Run the plugin, most likely within a DOM ready function.
" Get it started with `$('.lazyYT').lazyYT();`"

Please can you show an example of how to add that code (in a DOM?) and where to put it.

I have no doubt it will help many more folks with the same problem as me :-)
Thanks.
Mark Gavagan's avatar
Mark Gavagan
Hi @Tim.

I'm a novice and struggling with this, but https://learn.jquery.com/using-jquery-core/document-ready/ has some info that might help:

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready. ... Experienced developers sometimes use the shorthand $() for $( document ).ready()

So, I think $('.js-lazyYT').lazyYT(); is the needed DOM-ready function in shorthand.

Again, I'm a novice, so assume I likely have something wrong here.
Mark Gavagan's avatar
Mark Gavagan
Okay @Tim, I just tried it and it worked for me.

Right near the end of your code:



$('.js-lazyYT').lazyYT();

Best of luck! -Mark
Mark Gavagan's avatar
Mark Gavagan
@Tim

I will try again:

`

$('.js-lazyYT').lazyYT(); `
Albertovilva's avatar
Albertovilva
For those having trouble with foundation reveal here is a simple solution. Dont use the plugin, instead do this, this goes for foundation 6 but should work with any plugin.

1.Set the video URL in a data-video attribute.


2. Execute this javascript on load
$(".reveal").on("open.zf.reveal", function () {
var video_url = $(this).find(".video-yt").data('video');
$(this).find(".video-yt").attr('src', source);
});

This will leave the videos empty but with the url associated to them. Once the Reveal opens it sets the youtube url to the iframe so it loads. Much better than lazy loading with an image and extremely efficient :)
Jonas's avatar
Jonas
Hi

please note that the demo domain has expired, and is now linking to ads

Kind regards
Jonas
Mark's avatar
Mark
Youtube videos that are cropped with a parameter like yt:crop=4:6 do not have thumbnails generated.

This one for example will not have a preview thumbnail generated by the script: https://www.youtube.com/watch?v=YD76kXRjtc4

Leave a comment