V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
rizon
V2EX  ›  程序员

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

  •  
  •   rizon ·
    othorizon · 2019-06-10 23:44:39 +08:00 · 1699 次点击
    这是一个创建于 1753 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现在有一段动态获取的前端代码,想要放到页面中去加载。
    那么使用 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);
    
    3 条回复    2019-06-18 09:49:51 +08:00
    Takamine
        1
    Takamine  
       2019-06-10 23:57:08 +08:00 via Android
    是我的话,我会用第二种。
    难道因为我是后端吗 23333。(。ò ∀ ó。)
    ysc3839
        2
    ysc3839  
       2019-06-11 05:23:43 +08:00 via Android
    具体应该看内容的,append 一般用于不是一个完整页面的情况吧,可以直接复用当前页面的 css。
    xizon
        3
    xizon  
       2019-06-18 09:49:51 +08:00
    感觉能避免 iframe 尽量避免~ 也可以考虑 ajax 异步的方法,如果动态输出的内容包含了 html 结构,可以考虑使用模板引擎,比如 template7,具体看情况咯
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5730 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 01:51 · PVG 09:51 · LAX 18:51 · JFK 21:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.