在IFRAME中动态更新JavaScript后重置状态

Resetting state after dynamically updating JavaScript in an IFRAME

本文关键字:状态 JavaScript 更新 IFRAME 动态      更新时间:2023-09-26

我正在制作一个简单的web应用程序,动态创建一个包含HTML, JavaScript和CSS的网页。通过一个IFRAME中的一些基本UI,我让用户选择选项,然后在另一个IFRAME中每次发生变化时创建页面。我用这样的代码重建页面:

var iframe = document.getElementById('output_frame');
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html_content);
iframe.contentWindow.document.close();

它非常适合静态内容,但我也包括了一堆第三方库,虽然提供的功能在第一次创建页面时工作得很好,但在随后的更改中,它们会中断。例如,帧率计数器开始于60hz左右,但在每个更改/更新周期后迅速上升。

当我将页面写入磁盘并正常加载时,当然一切正常。

我想这是因为这样更新iframe与页面加载几乎不一样,并且不会重置它需要的所有内容。

内容改变后,我试着打电话给reload(true) on the IFRAME.contentWindow,但似乎没有帮助。

我是否应该以不同的方式更新IFRAME,如果没有,是否有方法重置更新之间的状态。

谢谢。

我替换了之前部分有效的代码:

var iframe = document.getElementById('output_frame');
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html_content);
iframe.contentWindow.document.close();

使用这段代码,现在一切都按预期工作了。谢谢你@CBroe

// remove old frame
var old_iframe = document.getElementById('output_frame');
old_iframe.parentNode.removeChild(old_iframe);
// create new one - CSS takes care of position, size etc.
var new_iframe = document.createElement('iframe');
new_iframe.id = "output_frame";
new_iframe.frameBorder = 0;
// update the contents
document.body.appendChild(new_iframe);
new_iframe.contentWindow.document.open()
new_iframe.contentWindow.document.write(html_content);
new_iframe.contentWindow.document.close();

它似乎有点慢,但现在,任何与JavaScript我加载作为页面的一部分工作如预期的