Saturday, August 16, 2014

Prevent FOUC in AngularJS using resolve

Flash of Unstyled Content (FOUC) happens in the below scenarios
  • When the application is initially loading and AngularJS has not loaded yet
  • When AngularJS is fetching data from the server

In the above scenarios user may see flashes of pages without data or see data slowing getting loaded. Hence for better user experience we should avoid this.

As you know AngularJS provides ng-cloak to handle FOUC and this is needed when the AngularJS is not loaded (first scenario above).

For the second scenario where we need avoid FOUC , Angular provides a mechanism when it is fetching data from the server. This is done using resolve feature. The resolve ensures that the controller and data is properly loaded before AngularJS binds the view. When we fetch data using resolve, Angular waits till the data is fetched and thereby avoiding FOUC.

Here is the sample code which utilizes resolve to fetch data from the server.

        .when("/contact", {
            templateUrl: "/app/contact/contact.html",
            controller: "contact",
            controllerAs: "vm",
            resolve: ['contactService', function (contactService) {
                return contactService.resolve();

As you see resolve is used in the routing and here I am specify that the controller loading need to wait till the service fetches data from the server.

No comments:

Post a Comment