更新时间:2023-12-01 23:02:46
自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.