• 请不要在回答技术问题时复制粘贴 AI 生成的内容
rizon
V2EX  ›  程序员

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

  •  
  •   rizon ·
    othorizon · Jun 10, 2019 · 2134 views
    This topic created in 2528 days ago, the information mentioned may be changed or developed.

    现在有一段动态获取的前端代码,想要放到页面中去加载。
    那么使用 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 replies    2019-06-18 09:49:51 +08:00
    Takamine
        1
    Takamine  
       Jun 10, 2019 via Android
    是我的话,我会用第二种。
    难道因为我是后端吗 23333。(。ò ∀ ó。)
    ysc3839
        2
    ysc3839  
       Jun 11, 2019 via Android
    具体应该看内容的,append 一般用于不是一个完整页面的情况吧,可以直接复用当前页面的 css。
    xizon
        3
    xizon  
       Jun 18, 2019
    感觉能避免 iframe 尽量避免~ 也可以考虑 ajax 异步的方法,如果动态输出的内容包含了 html 结构,可以考虑使用模板引擎,比如 template7,具体看情况咯
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3300 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 11:46 · PVG 19:46 · LAX 04:46 · JFK 07:46
    ♥ Do have faith in what you're doing.