Snippets

YouTube Lazy Loader

Put that script on your site, then make an anchor element like this:

<a class="youtube-link" href="video-page">Video Title</a>

JQuery will replace your anchor with a lightweight video that will loaded only when you click!

You have to add this CSS too:

.youtube-box,
.youtube-frame {
  display:block;
  width:420px; /* video width */
  height:315px; /* video height */
  background-color:black;
  background-size:100%;
  position:relative;
  border:none;
  margin:0px auto 15px;
}

.youtube-box span {
  display:block;
  position:absolute;
  top:0px;
  right:0px;
  bottom:0px;
  left:0px;
}

.youtube-box .youtube-title {
  background-color:rgba(0,0,0,0.4);
  font:bold 15px Verdana,Arial,Sans-Serif;
  color:white;
  text-shadow:0px 1px 2px black;
  bottom:auto;
  line-height:30px;
  height:30px;
  overflow:hidden;
  padding:0px 15px;
}

.youtube-box .youtube-bar {
  background:black url('yt-bar-center.png') repeat-x top;
  height:35px;
  top:auto;
}

.youtube-box .youtube-bar .yt-bar-left {
  background:transparent url('yt-bar-left.png') no-repeat top left;
}

.youtube-box .youtube-bar .yt-bar-right {
  background:transparent url('yt-bar-right.png') no-repeat top right;
}

.youtube-box .youtube-play {
  cursor:pointer;
  width:83px;
  height:56px;
  top:50%;
  left:50%;
  margin:-28px 0px 0px -42px;
  background:transparent url('yt-play.png') no-repeat top left;
}

.youtube-box .youtube-play:hover {
  background-position:bottom left;
}

$(function() {
    $('a.youtube-link').each(function() {
        var yt_url   = this.href,
            yt_id    = yt_url.split('?v=')[1],
            yt_title = $(this).text();
        $(this).replaceWith('<div class="youtube-box" style="background-image:url(http://img.youtube.com/vi/' + yt_id + '/0.jpg);"><span class="youtube-title">' + yt_title + '</span><span class="youtube-bar"><span class="yt-bar-left"></span><span class="yt-bar-right"></span></span><span class="youtube-play"></span></div>');
        $('div.youtube-box').click(function() {
            $(this).replaceWith('<iframe class="youtube-frame" src="http://www.youtube.com/embed/' + yt_id + '"></iframe>');
        });
    });
});

Source: http://hompimpaalaihumgambreng.blogspot.com/2012/05/youtube-...

Share this snippet

 
  • http://rawrviking.com Rawr

    That’s pretty nice. Gotta have that lazy function on one of my sites :)