Skip to content

Instantly share code, notes, and snippets.

@dipakcg
Created April 5, 2020 05:17
Show Gist options
  • Save dipakcg/8bf7e4155fd55e71c6f7c3e28e286f4a to your computer and use it in GitHub Desktop.
Save dipakcg/8bf7e4155fd55e71c6f7c3e28e286f4a to your computer and use it in GitHub Desktop.
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="https://www.youtube.com/watch?v=nEFZLFyZNcE?rel=0" frameborder="0" allowfullscreen style="border:0"></iframe>
</div>
(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:
----------------------
<script>
function init() {
var vidDefer = document.getElementsByTagName('iframe');
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute('data-src')) {
vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src'));
}
}
}
window.onload = init;
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment