Search code examples
backbone.jswidgetdocument.writehamlc

Backbone.js not performing document.write at the correct time?


I have a backbone.js CMS of sorts, that accepts html and then renders it in the browser. The following is the template file (in .hamlc) that renders the backbone page object.

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

This works fine, until I have a <script> tag. I have a script tag for a widget (below)

<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>

This widget uses document.write (which you can see if you look at the source). First, when I load the page it doesn't show anything (I've tested the widget in an html file by itself and it displays their normal god-awful ). When I inspect the element, it looks like the script tag was removed.

However, when I test with the following:

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

It runs. Still nothing in the inspector though.

Finally, testing with the following:

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

It also runs. However, it completely destroys the page content and just shows 'test'.

According to this article about using document.write for widgets, it says it can't be run after the page load. I'm assuming that's what's happening here is that document.write is being run after page load and destroying all the content, given that's the technique backbone.js uses (appending/replacing elements in the DOM once the page is loaded).

How can I make my Backbone.js CMS accept script tags with document.write widgets without either not showing anything or destroying the entire page?


Solution

  • You're calling document.write after the page has been loaded, so it'll overwrite the whole page. You could try putting the script tag in an iframe, or monkey patch document.write to behave differently after the page has been loaded. See the top answer on this question:

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