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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM