Search code examples
angularjsangular-ui-routerpreload

How I preload a state in angularjs uirouter without navigating to it?


I'm working on an application in angularjs with multiple pages using uirouter. After loading the page belonging to the current state, I wish to preload the other pages on the background, so that when a user select one of those pages they appear instantly on the screen.

I've tried looking for options on how to do this by searching the web, the uirouter documentation and stack overflow I couldn't find anything helpful.

Is there a way to preload an uirouter view without navigating to that view (making it visible)?


Solution

  • Unless you're actually fetching complete HTML pages in angularJS (I doubt it) you're loading data via API's that will get inserted into packaged HTML files/templates.

    The way I accomplish this is by triggering my service (I use factories) to get data via HTTP and cache it. You can cache either by storing the fetched data in a variable inside the factory (where it can be accessed by multiple controller/directives) or by simply using the cache:true parameter on your HTTP call, like so:

    factory.getDataForPage = function() {
      var url = "/api/data.json";
      var request = $http({
        method: "get",
        params: {},
        url: url,
        cache: true
      });
      return (request.then(rs.handleSuccess, rs.handleError));
    }
    

    In that case you're returning the data to your controller, but you could easily store it in the factory as well and then put in logic to check if that data already existed before executing the HTTP call.

    Long winded explanation - you don't precache pages (essentially the HTML is already precached) - you precache data