![](/img/trans.png)
[英]File upload with hidden iframe - How to detect dropped connection in Javascript?
[英]Detect connection issues in iframe
這個問題與在不同 iframe 標簽中調用不同頁面的 html 文件有關。 有沒有辦法,可能使用 JavaScript 來檢查頁面是否存在連接問題? 如果是,則嘗試重新加載此幀,直到建立連接。
更清楚一點,如果您查看以下鏈接( http://tvgl.barzalou.com )(即使內容是法語,您也會注意到頁面的不同部分加載的方式,並且加載的頻率高於不,正確加載)。 但偶爾,在周末,網絡連接出現輕微問題,出於某種原因,框架會發出這個可笑的灰色/淺灰色圖標,表示存在連接問題。 當然,當頁面被手動重新加載時,框架會恢復生機。
您可以安排一個代碼來檢查 iframe 是否正確加載
考慮一個樣本
<script language="javascript">
var attempts = 0;
var maxattempt = 10;
var intid=0;
$(function()
{
intid = setInterval(function()
{
$("iframe").each(function()
{
if(iframeHasContent($(this)))
{
//iframe has been successfully loaded
}
if(attempts < maxattempt)
{
attempts++;
}
else
{
clearInterval(intid);
}
})
},1000);
})
function iframeHasContent($iframe)
{
if($iframe.contents().find("html body").children() > 0)
{
return true;
}
return false;
}
</script>
這個簡單的代碼片段將檢查文檔中的 iframe 是否已正確加載。 它將嘗試此操作 10 次,然后將中止檢查。
當檢查中止時,您可以為每個 iframe 調用 iframeHasContent() 以列出尚未加載的那些,並在需要時重新加載它們。
請檢查更新的代碼,該代碼將在達到最大嘗試次數后檢查並重新加載 iframe...
<script language="javascript">
var attempts = 0;
var maxattempt = 10;
var intid=0;
$(function()
{
intid = setInterval(function()
{
$("iframe").each(function()
{
if(iframeHasContent($(this)))
{
//iframe has been successfully loaded
}
if(attempts < maxattempt)
{
attempts++;
}
else
{
clearInterval(intid);
checkAndReloadIFrames();
}
})
},1000);
})
function iframeHasContent($iframe)
{
if($iframe.contents().find("html body").children() > 0)
{
return true;
}
return false;
}
function checkAndReloadIFrames()
{
$("iframe").each(function()
{
//If the iframe is not loaded, reload the iframe by reapplying the current src attribute
if(!iframeHasContent($(this)))
{
//reload iframes if not loaded
var $iframe = $(this);
var src = $iframe.attr("src");
//code to prevent cache request and reload url
src += "?_" + new Date().getTime();
$iframe.attr("src",src);
}
});
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.