简体   繁体   English

替换 document.write 以将 HTML 内容放置在 iframe 中

[英]Replace document.write to place HTML content inside an iframe

I have a JavaScript script (no plugins, just pure JS) that creates an iframe element in the body of the page, and inside this iframe is placed a huge HTML to be displayed in this iframe.我有一个 JavaScript 脚本(没有插件,只是纯 JS),它在页面主体中创建了一个 iframe 元素,在这个 iframe 内部放置了一个巨大的 HTML 以在这个 iframe 中显示。

This script uses document.write to write this content to the iframe, however, performance tools report that this procedure is too slow to load the page.此脚本使用 document.write 将此内容写入 iframe,但是,性能工具报告此过程太慢而无法加载页面。

Below is my code:下面是我的代码:

var body = document.getElementsByTagName('body'),
    iframe,
    container;

container = document.createElement('div');
container.id = 'iframePlaceholder';

iframe = document.createElement('iframe');
iframe.id = 'myPageIframe';
iframe.name = 'page-content-frame';
iframe.allowfullscreen = true;

container.appendChild(iframe);
body[0].appendChild(container);

iframe = document.getElementById('myPageIframe');

iframe.contentWindow.document.open();
iframe.contentWindow.document.write('<html><body>content........<script src="..."></script></body></html>');
iframe.contentWindow.document.close();

What can I do to avoid using document.write without having to rewrite all my HTML in DOM?我该怎么做才能避免使用 document.write 而不必在 DOM 中重写我的所有 HTML?

Is it possible to convert this HTML string into a DOM element and add it to the iframe?是否可以将此 HTML 字符串转换为 DOM 元素并将其添加到 iframe 中?

Edit:编辑:

The content loaded by the iframe is dynamic, so it is not possible to place an HTML file to be loaded by the iframe's SRC. iframe 加载的内容是动态的,所以不可能放置一个 HTML 文件由 iframe 的 SRC 加载。

Perhaps you can try placing the HTML content inside a new file and add the name of the file to the src attribute of the iframe.也许您可以尝试将 HTML 内容放在一个新文件中,并将文件名添加到 iframe 的 src 属性中。

Something like the following:类似于以下内容:

<iframe id="myPageIframe" name="page-content-frame" src="newfile.html"></iframe>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM