2015-02-06 48 views
0

我目前使用document.write來將html注入到我的框架中。我使用Backbone,Marionette,require.js,jQuery。避免document.write?任何替代品?

我想避免使用document.write,因爲它有性能和瀏覽器的影響。

請提出替代方案。

我當前的代碼:

var html = this.compilePageHtml(); //We get some HTML code 
    this._previewWindow = window.open("about:blank", "PreviewWindow","width=320, height=570, scrollbars=yes"); 
    this._previewWindow.document.write(html); //Loads HTML in new window popup 
+2

爲什麼不使用'的.html()',而不是..的 – qtgye 2015-02-06 05:40:58

+0

可能重複(http://stackoverflow.com/questions/4537963/what-are-alternatives-to-document-write) – 2015-02-06 05:46:54

+0

在jQuery中:$(this._previewWindow.document).html(html); – MaxZoom 2015-02-06 05:52:48

回答

2

你可以使用上的新窗口的身體.innerHTML財產。

this._previewWindow = window.open("about:blank", "PreviewWindow","width=320, height=570, scrollbars=yes"); 
this._previewWindow.document.body.innerHTML = html; 

演示:?[?什麼是替代使用document.write] http://jsfiddle.net/jfriend00/g9e8rg7h/

+0

這將替換body元素中的html,而它應該是文檔。 – MaxZoom 2015-02-06 05:54:01

+1

@MaxZoom - 它取決於OP的html是什麼(他們沒有透露)。一個新的窗口/文檔被賦予一個框架體,所以這段代碼將設置正文HTML。是的,你也可以設置document.documentElement HTML。 – jfriend00 2015-02-06 05:59:06

+0

我添加了'this._previewWindow.document.close();'它瞬間加載(而不是4-5秒的滯後),但是我得到了jquery.mobile加載頁面的錯誤。這是div'

Error Loading Page

'一切似乎都正常,但我不明白爲什麼我有這個錯誤。 – VRD 2015-02-06 09:01:26