Defer Youtube videos

Joined
Aug 2, 2017
Messages
156
Likes
96
Degree
0
Hi!

Youtube videos are pretty bad for site speed.

I saw this post and I think that it's a good idea to defer them.

If you use the iframe code from youtube here's an easy way to do it automatically in wordpress:

PHP:
//Youtube DEFER

add_filter('the_content', 'filter_youtube_videos');
function filter_youtube_videos($content) {
    return str_replace('iframe src="//www.youtube.com', 'iframe src="" data-src="//www.youtube.com', $content);
}

And the JS from the post:

JavaScript:
<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>

Main improvement is in "time to interactive".

Do you think is worth it?

Thanks!
 
If you're using Wordpress's oEmbed that calls wp-embed.js, then you're already deferring the loading of Youtube videos because wp-embed.js is deferred. It's the final script that loads in the enqueued process through wp_footer().

oEmbed is when you simply paste the URL of the Youtube video in your post, versus taking the time to get the embed <iframe> script from the Youtube page. oEmbed fetches that for you.

This is and was a good idea, but Wordpress added oEmbed in version 2.9 on December 19, 2009. That post was written December 14, 2015. Six years after the fact. Not sure what their goal was with that post, but it's already taken care of for you.
 
Back