如何防止YouTube JS调用减慢页面加载速度 [英] How to prevent YouTube js calls from slowing down page load
问题描述
我正在使用 https://gtmetrix.com 诊断我的页面速度问题.
I am using https://gtmetrix.com to diagnose issues with my page speed.
相关页面中有一个嵌入式YouTube视频和GTMetrix表示,该视频的JS调用正在减慢页面加载速度.
The page in question has one embedded YouTube video and GTMetrix is saying that this video's JS calls are slowing down page load speed.
正在拨打电话:
<iframe width="640" height="360" src="https://www.youtube.com/embed/PgcokT0AWHo" frameborder="0" allowfullscreen></iframe>
推荐答案
自2019年10月起,此方法不再起作用(感谢@CpnCrunch进行更新).对于以下情况它不会影响用户体验,您显然可以在页面加载后添加1000毫秒的超时,以使其生效.
as of October 2019, this is not working anymore (Thanks to @CpnCrunch for the update). For the cases where it's not impacting the user experience, you can apparently add a 1000ms timeout after the page load for it to take effect.
这是使用纯JS解决方案在页面加载时动态添加src
的示例.使用事件监听器代替window.onload
,因为对于后者,只能设置一个事件,它将覆盖任何先例的window.onload
事件:
This is an example of attibuting the src
dynamically on page load, using a pure JS solution. Using event listeners instead of window.onload
because with the latter, only one event can be set and it would override any precedent window.onload
event:
<iframe id="videoFrame" width="640" height="360" src="" frameborder="0" allowfullscreen></iframe>
<script>
function setVideoFrame(){
document.getElementById('videoFrame').src = 'http://example.com/';
}
if (window.addEventListener) // W3C DOM
window.addEventListener('load', setVideoFrame, false);
else if (window.attachEvent) { // IE DOM
window.attachEvent('onload', setVideoFrame);
}else{ //NO SUPPORT, lauching right now
setVideoFrame();
}
</script>
请注意,脚本可以在代码中的任何位置,但是在不支持事件侦听器的情况下(对于当今的浏览器来说这是极不可能的),该函数应立即启动,因此至少应在
Note that the script can be anywhere in the code, but in case of no support for event listeners (which is highly unlikely with nowadays browsers), the function is launched right away, so it should be at least after the iframe
element.
这篇关于如何防止YouTube JS调用减慢页面加载速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!