108 Followers
·
Follow

Image for post
Image for post

Faster page load by lazy loading youtube iframe embed.

Increase your page speed and Google rank with this simple change. It’s now become more important than ever to cut out load time where you can since Google gives preferential treatment to sites that load faster. You should be aiming for less than 2–3 seconds.

It’s no secret that youtube iframe embeds slow down your page load. If you’re not autoplaying the video, ask yourself why are you slowing down your initial page load when you don’t need to? Let’s lazy load the iframe when we need it.

If your client or yourself is experiencing a greater than 3 second load time and you’re looking for ways to bring that down, you can shave a second or two quite easily.

Step 1 | HTML

Format your html so it looks nice with a placeholder image (this should simulate a video, have a play icon etc so the user is enticed to click on it. Further more inside the wrapper it should also have styles to support your YouTube iframe (width, height, border, etc). Because the image will later be swapped with the iframe once a user clicks on it.

Tip ** Bootstrap has styles out of the box for responsive youtube iframe embeds. That is what the class names embed-responsive embed-responsive-4by3 are for.

<div class="youtube-video-place embed-responsive embed-responsive-4by3 " data-yt-url="https://www.youtube.com/embed/BjngNWP9C5s?rel=0&showinfo=0&autoplay=1">

Step 2 |Scripts

Note i’m using jQuery here for convenience. First store the wrapper div in a variable. Then check to see if it exists. If it does create a click event on the wrapper. Once a user clicks on the wrapper adjust the html of the element and inject the iframe that pulls the embed url from the data attribute.

var video_wrapper = $('.youtube-video-place');

The reason I use a data attribute is because if you need to dynamically set the youtube video from a CMS you can by simply filling in the data-yt-url attribute with the full embed url.

That’s all there is to it. You just shaved a second or two off your Google Page Speed Insights score.

Want to see an example? First image is before the user clicks and second is after. Here is a live site I built that uses the technique: https://zzonehomes.ca/

Image for post
Image for post
Image for post
Image for post

As always if you need a developer to help you craft that website or web application that focuses on design, user experience and SEO i’m your guy.

Thanks!

Written by

I build websites & apps for ambitious clients over at FireScript https://firescript.ca — Want to work together? Send me a message!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store