Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Defer Youtube Video
This is the technique I use to defer Youtube videos, when optimising the performance of WordPress site.
(1) Replace Youtube iFrame embed code with the below one:
<div class="dcg-responsive-container">
<iframe class="dcg-responsive-iframe" src="" data-src="" frameborder="0" allowfullscreen style="border:0"></iframe>
(2) Add the following CSS element (stylesheet element that will make Youtube iFrame Responsive) (style.css?):
.dcg-responsive-container {
position: relative;
overflow: hidden;
padding-top: 56.25%;
.dcg-responsive-iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
(3) Add the following Javascript to the footer of the page:
function init() {
var vidDefer = document.getElementsByTagName('iframe');
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute('data-src')) {
window.onload = init;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment