Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you Defer Parsing of JavaScript for YouTube video on a WordPress site?

I just today realized that of my 1.2 MB site (per GTMetrix), 550k of it is a YouTube video.

My web site is a WordPress site, and the current video loads in an iframe.

I want my site to load faster... And not sure how to proceed. If I can make the YouTube video not load until clicked, and just have a thumbnail there instead, it seems like that would be the right play?

like image 419
Michael Grippi Avatar asked Aug 10 '16 04:08

Michael Grippi


People also ask

How do I defer external JavaScript in WordPress?

It gives you a simple way to defer parsing JavaScript using either async or defer. To get started, you can install and activate the free plugin from WordPress.org. Then, go to Settings → Async JavaScript to configure the plugin. At the top, you can enable the plugin's functionality and choose between async and defer.

How do you defer a youtube embed?

Go to your video on Youtube, right click and select "Copy Embed Code". Now make these two changes: Change the src="https://www.yo..." to data-src="https://www.yo..." Add a new src=""


1 Answers

1. Replace “scr” with “data-src”

<iframe width="560" height="315" data-src="https://www.youtube.com/embed/123456789" frameborder="0" allowfullscreen></iframe>

2. Add Javascript

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;

Now your site will load faster compared to past.

I have following this blog and it's working for me : http://www.codecanal.com/defer-parsing-javascript-youtube-videos/

like image 173
Shown Marsh Avatar answered Sep 19 '22 04:09

Shown Marsh