Search code examples
asynchronousmeteormeteor-blaze

Meteor Blaze : dont wait for child template rendering before rendering parent


playing with Blaze i realized the following : if i have a parent template where i include a child template with {{> child_template }}

then Blaze will wait for child template to be rendered before rendering parent. This can be good in some cases but not all.

For e.g if my parent template contains a <h1>Welcome to my page</h1> and child a list of 10 000 items. I would like a way to display <h1> asap and wait for the 10 000 items to appear later

what i'm doing currently to manage that is the following :

Template.parent.onRendered(function(){
    Blaze.render(Template.child, document.body);
});

it is working but i wonder if anyone have a better solution for this problem that seems pretty common. thanks


Solution

  • You could pass a custom boolean argument to the child component that's false by default, but the parent component's onRendered sets it true. And the child component should check this argument and not render anything unless it's true.

    Template.parent.onCreated(function() {
      this.state = new ReactiveDict();
      this.state.setDefault({
        "canRender": false,
      });
    }
    
    Template.parent.onRendered(function() {
      this.state.set("canRender", true);
    }
    
    Template.parent.helpers({
      canRender() {
        return Template.instance().state.get("canRender");
      }
    });
    

    Pass the state to the child component:

    <template name="parent">
      {{>child canRender=canRender}}
    </template>
    
    <template name="child">
      {{#if canRender}}
        <p>Millions of items go here.</p>
      {{/if}}
    </template>