程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了iframe 加载事件触发两次大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决iframe 加载事件触发两次?

开发过程中遇到iframe 加载事件触发两次的问题如何解决?下面主要结合日常开发的经验,给出你关于iframe 加载事件触发两次的解决方法建议,希望对你解决iframe 加载事件触发两次有所启发或帮助;

绑定到 (@load="MyFunction") 的函数在创建 iframe 时触发一次,在实际加载时触发一次。

为什么在创建 iframe 时会触发它,以及如何避免它?

<template>
  <Transition name="modal">
    <div v-if="webvIEwOpen">
      <Transition name="content" appear>
        <div v-if="webvIEwOpen">
            <Transition name="iframe">
            <iframe
              v-show="showiframe"
              :src="webvIEwUrl"
              @load="iframeIsLoaded"
            />
          </Transition>
        </div>
      </Transition>
    </div>
  </Transition>
</template>

<script>
import { mapState } from 'vuex'

export default {
  data () {
    return {
      showiframe: false
    }
  },computed: {
    ...mapState({
      webvIEwOpen: state => state.webvIEw.open,webvIEwUrl: state => state.webvIEw.url
    })
  },watch: {
    webvIEwOpen () {
      setTimeout(() => {
        this.showiframe = true
      },1000)
    }
  },methods: {
    iframeIsLoaded () {
      console.log('iframe loaded')
    }
  }
}
</script>

解决方法

这似乎是一个 web kit 问题,它会触发两次 (safari/chromE),因为它在添加到 DOM(父级上的 v-if)和加载内容时触发。将 .once 修饰符添加到 @load.once="MyFunction()"

可能会有所帮助 ,

我们从您的 linked answer 得知 Chrome 会显示此问题,除非您在将 iframe 附加到 DOM 之后附加侦听器。为此,我们可以利用 Vue 的 lifecycle hooks。我们希望它在 iframe 添加到 DOM 之后发生,但在它有机会加载之前发生,因此我们将使用 updated 钩子。

我在我的任何浏览器中都没有遇到过这个问题,所以很遗憾我无法真正为您测试。自己测试一下,看看这样的事情是否可以为您解决:

<template>
  <label for="show">Show iFrame</label>
  <input id="show" type="checkbox" v-model="webviewOpen">
  <div v-if="webviewOpen">
    <iframe
      src="https://motherfuckingwebsite.com/"
      @load="iframeLoadHelper"
      frameborder="0"
    ></iframe>
  </div>
</template>

<script>
export default {
  name: 'App',data() {
    return {
      webviewOpen: false,iframeReady: false
    };
  },methods: {
    // Helper method,just to keep 'if' outside of the logic of your potentially
    // complex @load method
    iframeLoadHelper() {
      if (this.iframeReady) return this.iframeLoaded();
      else return; // do nothing
    },// The real load method
    iframeLoaded() {
      console.log('iframe loaded');
    }
  },updated() {
    console.log('changing ready-state');
    this.iframeReady = this.webviewOpen;
  }
};
</script>

<style>
:root { font-family: sans-serif; }
</style>
,

正如@tao 所建议的那样,还有其他东西会干扰,即 Nuxt Lazy Load 包。因此,如果有人使用此包并发现 iframes onload 事件神秘地触发两次并找到此线程:

iframes: false 部分中导入包时,在您的 nuxt.config.js 中添加 @H_970_3@modules。问题解决了!

大佬总结

以上是大佬教程为你收集整理的iframe 加载事件触发两次全部内容,希望文章能够帮你解决iframe 加载事件触发两次所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。