3/20/16

AngularJS SPA Splash View to prevent Blank or Flicker Effect During App Initialization

Depending on network latency and the number of components that an AngularJS SPA contains, the application can initially just show static HTML content until AngularJS completes its initialization process and compiles the HTML/DOM to show the dynamic content as intended. This usually causes a flicker as empty or unbound content is displayed before the dynamic content is bound to the view.

To better understand what happens, let’s take a look at an example of a SPA that takes a couple of seconds to load. This delays causes the app to display the uninitialized state of the application or static content.

Slow initialization with no splash view

As we can see in the example, the static content is displayed with some missing content that is only added after the app is initialized.  The content in the brackets can be replaced by using the ngBind directive, but this only removes the brackets and empty content is displayed instead.

Note that to simulate a delay, we are manually loading the app using angular.bootstrap and a timeout to bootstrap the app onto the DOM.


//simulates the delay in loading the app/module
 setTimeout(function () {
                angular.bootstrap( document, [ "app" ] );
            },2500);



Now that we see the challenge, let’s review how the AngularJS initialization process works:

AngularJS Initialization Process

The initialization process consists of the following steps:

  • Browser loads the static HTML content. (DOMContentLoaded event)
  • AngularJS 
    • Looks for the ngApp directive (automatic initialization)
    • Loads the module associated with the ngApp directive
    • Creates the injectors
    • Compiles the DOM to create the dynamic HTML content
With the understanding on how the initialization process works, we can make changes and improve the user experience by providing a splash view while our app is loading.  A simple splash view can be implemented by adding HTML static content that is displayed while the app initializes. Once the app is initialized, we use the ngIf directive to remove the splash content.

To hide the app content and prevent flickering, we use the ngCloak directive which helps us prevent displaying any un-compiled (HTML with directives but no data) HTML content. This is what hides the app and controller content until the initialization process is complete.


With these changes, we can now see how the loading app animation is displayed while the app is initializing. Once the app executes its run function, the $rootScope variables are set, and the ngCloak directive is removed by AngularJS from the DOM which makes the app elements visible. 

I hope that this provides some insight on AngularJS initialization process and how to provide a loading views to your apps.

Thanks.

1 comment :

  1. This comment has been removed by a blog administrator.

    ReplyDelete