Backbone.js没有在正确的时间执行document.write?

时间:2013-06-17 16:28:35

标签: backbone.js widget document.write hamlc

我有一个backbone.js CMS,它接受html,然后在浏览器中呈现它。以下是呈现主干页面对象的模板文件(在.hamlc中)。

%h1.text= @page.get('title')
.text.page-content!= @page.get('content')

这样可行,直到我有<script>标记。我有一个小部件的脚本标签(下面)

<script src='http://www.opentable.com/frontdoor/default.aspx?rid=52900&restref=52900&bgcolor=8AA86B&titlecolor=0F0F0F&subtitlecolor=0F0F0F&btnbgimage=http://www.opentable.com/frontdoor/img/ot_btn_black.png&otlink=FFFFFF&icon=light&mode=short&hover=1'></script>

此小部件使用document.write(如果您look at the source,则可以看到)。首先,当我加载页面时,它没有显示任何内容(我已经在一个html文件中自己测试了这个小部件,它显示了他们正常的上帝可怕)。当我检查元素时,看起来脚本标记已被删除。

但是,当我使用以下内容进行测试时:

<script type="text/javascript">
    alert(0);
</script>

它运行。尽管如此,检查员仍然没有。

最后,使用以下方法进行测试:

<script type="text/javascript">
    document.write('test');
</script>

它也运行。但是,它完全破坏了页面内容,只显示了“测试”。

根据this article about using document.write for widgets,它表示在页面加载后无法运行。我假设这里发生的是document.write在页面加载后运行并销毁所有内容,因为这是技术backbone.js使用(在加载页面后附加/替换DOM中的元素)。

如何让我的Backbone.js CMS接受带有document.write小部件的脚本标签,而不会显示任何内容或破坏整个页面?

3 个答案:

答案 0 :(得分:2)

我无法重现它,模板应该呈现:

$ coffee
coffee> hc = require './src/hamlc'
{ compile: [Function],
  template: [Function],
  __express: [Function] }
coffee> template = hc.compile ".text.page-content!= @content"
[Function]
coffee> template(content: 'Hello <script>Script</script>')
'<div class=\'page-content text\'>Hello <script>Script</script></div>'

并且脚本标记是持久的。您是否安装了最新版本?

答案 1 :(得分:1)

如果我理解正确,您正在尝试在模板中包含窗口小部件的脚本标记,这意味着它在初始DOM准备好后插入。由于你提到的原因,这不起作用;当脚本执行时,它将替换DOM中的所有内容。

您需要在初始DOM完成之前加载脚本,即在&lt; head&gt;中。或者在&lt; body&gt;的开头。这反过来意味着您必须在服务器提供的初始HTML中包含脚本标记,而不是尝试在客户端动态生成脚本标记。

答案 2 :(得分:1)

您在加载页面后调用document.write,因此它将覆盖整个页面。您可以尝试将脚本标记放在iframe或monkey patch document.write中,以便在加载页面后表现不同。请参阅此问题的最佳答案:

Dynamically added JavaScript overwrite the html page view (not the code)