[英]How to load multiple iframes concurrently?
我想同时加载 10-15 个 iframe,这样它就可以在从 URL 接收到数据时呈现。
我曾尝试使用 async 函数,但在加载一次 iframe 后它仍然可以正常工作
这是代码:
<iframe src="" height="50" width="320" id="frame_1"></iframe>
<iframe src="" height="50" width="320" id="frame_2"></iframe>
<iframe src="" height="50" width="320" id="frame_3"></iframe>
<iframe src="" height="50" width="320" id="frame_4"></iframe>
<iframe src="" height="50" width="320" id="frame_5"></iframe>
<script>
async function loadIframe1() {
console.log(1)
document.getElementById('frame_1').src='file1.html';
}
async function loadIframe2() {
console.log(2)
document.getElementById('frame_2').src='file1.html';
}
async function loadIframe3() {
console.log(3)
document.getElementById('frame_3').src='file1.html';
}
async function loadIframe4() {
console.log(4)
document.getElementById('frame_4').src='file1.html
}
async function loadIframe5() {
console.log(5)
document.getElementById('frame_5').src='file1.html';
}
loadIframe1();
loadIframe2();
loadIframe3();
loadIframe4();
loadIframe5();
</script>
如果我理解正确,您希望一次显示所有 iframe。
您可以将 CSS 与display: none
,只要它们都加载完毕,请将它们重新设置为display: block
。
这是一种方法:
const iframes = document.querySelectorAll('iframe'); const allIframes = iframes.length; let iframeCounter = 0; for (let iframe of iframes) { iframe.onload = () => { iframeCounter++; if (allIframes === iframeCounter) { let css = window.document.styleSheets[0]; css.insertRule(` iframe { display: block; } `, css.cssRules.length); } } }
iframe { height: 200px; width: 100%; display: none; }
<iframe src="https://example.com"></iframe> <iframe src="https://example.com"></iframe> <iframe src="https://example.com"></iframe> <iframe src="https://example.com"></iframe> <iframe src="https://example.com"></iframe>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.