如何防止 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.
这是一个在页面加载时动态分配 src
的示例,使用纯 JS 解决方案.使用事件侦听器而不是 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>
请注意,脚本可以在代码中的任何位置,但如果不支持事件侦听器(现在的浏览器不太可能),该函数会立即启动,因此至少应该在 iframe
元素.
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屋!