Search code examples
ember.jsember-dataember-cli

Ember JS Implement a splash screen / loading startup screen


What is the best way to implement a loading screen in Ember 2.5? What I want to achieve is: show splash screen -> load data in background -> when DOM is ready, hide splash screen.

I tried several options, but I cannot achieve to hide the splash screen when the document is ready. I am loading a large table, so it will take some time to finish the DOM, so model-ready is not the right hook.


Solution

  • I did this by adding custom HTML (simple loading div) to the app/index.html:

    <body>
      <div class="loading-overlay" id="initialLoading"></div>
    
      {{content-for "body"}}
    
      <script src="assets/vendor.js"></script>
      <script src="assets/event.js"></script>
    
      {{content-for "body-footer"}}
    </body>
    

    Then I added the following to my app/application/route.js:

    actions: {
      loading(transition/* , originRoute*/) {
        let controller = this.get('controller');
        if(controller) {
          controller.set('currentlyLoading', true);
        }
        transition.promise.finally(function() {
          $("#initialLoading").remove();
          if(controller) {
            controller.set('currentlyLoading', false);
          }
        });
      }
    }
    

    In my app/application/template.hbs I also had to add the loading div:

    {{#if currentlyLoading}}
      <div class="loading-overlay"></div>
    {{/if}}
    

    So what does happen?

    1. index.html is loaded and no javascript is parsed yet: your loading screen is visible.
    2. index.html is loaded and your javascript has been parsed. ember.js calls the loading action and sets currentlyLoading to true: both loading screens are shown.
    3. the transition is complete, the first loading and second loading screen get removed
    4. for every transition that is now happening, the loading screen is shown. To remove this behaviour, remove the second loading screen logic.

    I hope it helps.