我有一个 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>
最佳答案
我会建议类似以下的内容。将您的逻辑放入可重用的方法中,该方法执行采用索引的 iframe 生成。从索引 0 开始调用它以显示第一个 iframe。然后,一旦 iframe 遇到加载事件,就使用下一个索引再次调用该方法来执行逻辑迭代。
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);
关于javascript - 依次渲染多个 iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61545996/