有时,当这个脚本在一个页面上执行时,特别是当浏览器第一次加载这个页面时,iframe的内容将在test.html中显示这个页面,但它将是一个较旧的页面,缺少一些从目录中手动加载的实际test.html所包含的更改。每次setInterval()运行时,iframe的内容仍然是过时的。
如果整个页面被刷新,比如通过单击刷新按钮,iframe的内容将被更新,setInterval()将导致iframe显示当前的test.html。然而,如果给定足够的时间,setInterval()有时会停止加载test.html的当前内容。
我怀疑答案可能与为什么建议避免。innerhtml有关?或者这里有什么问题,为什么innerHTML不工作?但我是一个极端的新手,并不能完全理解innerHTML的局限性。
<script>
// Loads into a div an iframe that itself loads a page from the server.
document.getElementById("divy").innerHTML="<iframe width='600' height='800' id='cat' src='test.html'></iframe>";
iframe = document.getElementById('cat');
//Scrolls iframe to bottom.
iframe.onload = function () {
iframe.contentWindow.scrollTo(0,iframe.contentWindow.document.body.scrollHeight);
console.log(iframe.contentWindow.document.body.scrollHeight);
}
refresh_rate = 3000
// Every refresh_rate miliseconds, replaces the html inside the div with a new iframe so any changes to the page test.html are now shown.
setInterval(function(){
var element = document.getElementById('cat');
element.parentNode.removeChild(element);
document.getElementById("divy").innerHTML="<iframe width='600' height='800' id='cat' src='test.html'></iframe>";
iframe = document.getElementById('cat');
var x = document.getElementsByTagName('*');
console.log(x)
iframe.onload = function () {
iframe.contentWindow.scrollTo(0,iframe.contentWindow.document.body.scrollHeight);
console.log(iframe.contentWindow.document.body.scrollHeight);
}
}, refresh_rate);
</script>
您的测试页面被缓存在某个地方,您需要在每次页面重新加载时中断缓存。我在您的代码的整理版本中添加了一个基本的缓存破坏器。
但是,更新iframe的src
属性要比每隔三秒取出整个元素并重新插入要简单得多。
<script>
function loadCat(cacheBuster){
document.getElementById("divy").innerHTML="<iframe width='600' height='800' id='cat' src='test.html?'+cacheBuster></iframe>";
var iframe = document.getElementById('cat');
//Scrolls iframe to bottom.
iframe.onload = function () {
iframe.contentWindow.scrollTo(0,iframe.contentWindow.document.body.scrollHeight);
console.log('iFrame height: ', iframe.contentWindow.document.body.scrollHeight);
}
}
function removeCat(){
var element = document.getElementById('cat');
element.parentNode.removeChild(element);
}
var refresh_rate = 3000;
var counter = 0;
loadCat(counter);
// Every refresh_rate miliseconds, replaces the html inside the div with a new iframe so any changes to the page test.html are now shown.
setInterval(function(){
removeCat()
loadCat(++counter);
}, refresh_rate);
</script>