How to prevent Html showing before knockout binding is executed
Here's a simple trick. Just make your root element initially hidden and set the visible binding to true.
<div style="display: none;" data-bind="visible: true">
<!-- the rest of your stuff -->
</div>
As it's rendered, before knockout does its thing, it will be initially hidden. When the bindings are applied, knockout will override the style and make it visible.
Alternatively, you can throw your view into a script block and instantiate it through a template. The script blocks will not be rendered but will be visible when knockout renders the template.
<!-- ko template: 'myView' --><!-- /ko -->
<script id="myView" type="text/html">
<!-- the rest of your stuff -->
</script>
Since the behavior you want often varies from page to page - this is what I am doing in my layout/template file (ASP.NET).
<div class="ko-unbound" data-bind="css: { 'ko-unbound': false, 'ko-bound': true }">
@RenderBody()
</div>
When the page is bound:
-
ko-unbound
class is removed from the page (initially added withclass
attribute). -
ko-bound
class is added to the page.
Then in a page where unwanted content is a problem I can customize the css to show or hide things based on these two classes. I also use this technique to show a 'loading' image or perhaps impose a minimum height for an element.
.ko-unbound #storeWizard
{
display: none; // hide entire section when the page is binding
}
.ko-bound #loadingGraphic
{
display: none; // hide loading graphic after page is bound
}
During testing, when applying bindings I add a timeout so I can see the flash.
setTimeout(function ()
{
ko.applyBindings(RR.VM);
}, 300);
Wrap your html in something like this -
<div id="hideme" style="display:none">
</div>
Then in your JavaScript, add the following jquery line after your apply binding -
$('#hideme').show();
This is simplest method that I've found that works. You could do this with some knockout bindings, but you lose guaranteed timing because you cannot control order bindings are executed.