gajus / youtube-player

YouTube iframe API abstraction.
Other
363 stars 80 forks source link

Add defer and async to injected script #59

Open felipefialho opened 7 years ago

felipefialho commented 7 years ago

Hey guys, how are you?

I'm testing a project in GTMetrix and it's asking to...

1.1MiB of JavaScript is parsed during initial page load. Defer parsing JavaScript to reduce blocking of page rendering.

https://www.youtube.com/yts/jsbin/player-vfltmLGsd/en_US/base.js (993.3KiB)
https://www.youtube.com/yts/jsbin/www-embed-player-vflw8vOVz/www-embed-player.js (80.2KiB)
https://www.youtube.com/embed/MoxIZNE4M8A?autoplay=1&controls=0&showinfo=0&modestbranding=0&loop=1&fs=0&cc_load_policy=0&autohide=0&rel=0&enablejsapi=1&origin=https%3A%2F%2Fcubo.network&widgetid=1 (2.7KiB of inline JavaScript)

Can you add the defer and async in injected script to resolve it?

Thanks 😄

gajus commented 7 years ago

The underlying library used to inject the script does not support defer attribute. I agree, though, it should be added.

Note though that this does not effect you if you load the main script bundle using defer.

felipefialho commented 7 years ago

I understand... I tried make some changes to improve it, but the result was not good..

jaysingh17 commented 6 years ago

If you find this type of issue. https://www.youtube.com/yts/jsbin/player-vfltmLGsd/en_US/base.js (993.3KiB) https://www.youtube.com/yts/jsbin/www-embed-player-vflw8vOVz/www-embed-player.js (80.2KiB)

<iframe src="https://www.youtube.com/embed/w47PU9ppuF8?rel=0" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe>

Step:-

In the above you need to replace the src by src="" and add youtube video url like this data-src="https://www.youtube.com/embed/w47PU9ppuF8"

So New code will be this

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

Now you tell browser to loads all the javascript files of embeded video after the page loads . Then you need to add the below code before the end of body tag

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