想要把一段前端代码动态加载到页面中是直接 append 元素还是放到 iframe 框架中?着急在线等!

2019-06-10 23:44:39 +08:00
 rizon

现在有一段动态获取的前端代码,想要放到页面中去加载。
那么使用 iframe 然后 write 内容,还是直接在页面 append 一个元素?
这两种方式哪种比较好?各有什么利弊??


使用 iframe

iframe = document.createElement('iframe');
            iframe.setAttribute('frameborder', '0');
            iframe.setAttribute('id', '123');
            iframe.setAttribute('width', '100%');
            iframe.setAttribute('height', '100%');
            document.getElementById("templateBody").appendChild(iframe);
            iframe.contentDocument.open();
            iframe.contentDocument.write(value);
            iframe.contentDocument.close();

append 到页面

$('#templateBody').html(value);
1712 次点击
所在节点    程序员
3 条回复
Takamine
2019-06-10 23:57:08 +08:00
是我的话,我会用第二种。
难道因为我是后端吗 23333。(。ò ∀ ó。)
ysc3839
2019-06-11 05:23:43 +08:00
具体应该看内容的,append 一般用于不是一个完整页面的情况吧,可以直接复用当前页面的 css。
xizon
2019-06-18 09:49:51 +08:00
感觉能避免 iframe 尽量避免~ 也可以考虑 ajax 异步的方法,如果动态输出的内容包含了 html 结构,可以考虑使用模板引擎,比如 template7,具体看情况咯

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/572642

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX