vue中使用iframe,加载完成的onload事件偶尔不触发

背景:项目中使用了iframe做预览,左侧预览,右侧编辑。

问题:页面加载时,会把一些值通过postMessage发给iframe指定的页面,这样实现预览。但通过实验6次进入可能有一次无法触发onload事件。代码如下
<template>
<div>
<iframe id="iframe" width="500" height="800" src="http://xxx"></iframe>
</div>
</template>
<script>
...
sendMsg () {
let iframe = document.querySelector('#iframe')
iframe.onload = () => {
console.log('加载完成') // 这里偶尔不会触发
}
}
...
</script>

解决:通过询问大神,知道了onload一定要在iframe加载前定义好。更改如下
<template>
<div id="iframeBox">
<iframe id="iframe" width="500" height="800"></iframe>
</div>
</template>
<script>
...
sendMsg () {
let iframeBox = document.querySelector('#iframeBox')
let iframe = document.createElement('iframe')
iframe.onload = () => {
console.log('加载完成') // 这样每次都会触发
}
iframe.src = 'http://xxx'
iframeBox.appendChild(iframe)
}
...
</script>

总结:一定要注意iframe绑定事件和加载时的顺序,先绑定事件再赋值src地址,才会每次都会触发onload

posted on 2020-04-04 15:14  daV_chen  阅读(14441)  评论(0编辑  收藏  举报

导航