【问题标题】:Rendering multiple iframes one after the other一个接一个地渲染多个 iframe
【发布时间】:2020-08-16 03:36:27
【问题描述】:

我有一个 url 数组,我想用它们在页面上呈现 iframe。我的目标是在显示下一个 iframe 之前显示 iframe 的内容,该过程一直持续到我为数组中的所有 url 呈现 iframe 为止。不知道我做错了什么,下面是我写的一个脚本来处理这个。适用于单个 url,但是对于多个 url,它会在页面上呈现任何 iframe 之前尝试从所有 url 中获取所有内容。

<script>
    get('endpoint to fetch the urls').then(data => { // makes api request to fetch the urls.
        const lti_launch_urls = data['lti_launch_urls'] 
        lti_launch_urls.forEach((launch_url, index) => {


                const iframe = document.createElement('iframe')
                iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms"
                iframe.width = "100%"
                iframe.frameBorder = "0"
                iframeId = "iframe-" + index
                iframe.id = iframeId
                iframe.src = launch_url
                document.body.appendChild(iframe)
                iframe.contentWindow.postMessage(style, "*");
        })

    })
</script>

【问题讨论】:

  • forEach 内部没有阻止逻辑阻止它继续迭代,直到加载 iframe。
  • @Taplar 你建议我如何阻止?
  • 您不一定需要创建阻塞逻辑,只需使用 iframe onload 事件加载下一个 iframe。

标签: javascript html jquery css iframe


【解决方案1】:

我建议如下。将您的逻辑拉入一个可重用的方法中,该方法执行采用索引的 iframe 生成。从索引 0 开始调用它以显示第一个 iframe。然后,一旦 iframe 遇到 load 事件,使用下一个索引再次调用该方法以执行逻辑迭代。

    const lti_launch_urls = data['lti_launch_urls'];
    const loadNextIframe = index => {
      if (index >= lti_launch_urls.length) return;

      const launch_url = lti_launch_urls[index];
      const iframe = document.createElement('iframe');

      iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
      iframe.width = "100%";
      iframe.frameBorder = "0";
      iframeId = "iframe-" + index;
      iframe.id = iframeId;
      iframe.src = launch_url;

      iframe.addEventListener('load', () => loadNextIframe(++index));

      document.body.appendChild(iframe);
      iframe.contentWindow.postMessage(style, "*");
    };

    loadNextIframe(0);

【讨论】:

    猜你喜欢
    • 2015-10-10
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多