Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preloading HTML partials into AngularJS UI-Router application

I notice that on a full refresh of my angular app, state transitions (I am using ui-router but then may be similar to native Angular routing as well) have a slight lag on first visit because the browser does a GET request to retrieve the HTML partial that is associated with that given state. All subsequent visits are basically instantaneous, but I want to know if there is a way to tell Angular to pre-load all the needed partials when first coming to the page?

Do they not do this because eventually too many partials would use too much bandwidth if fetched in parallel?

like image 475
Matt Hintzke Avatar asked Dec 05 '14 06:12

Matt Hintzke


2 Answers

You could put those partials inside a script tag, and place it in your main HTML page so they're all loaded up front. You could also load them in the run block of your app, and put them in the $templateCache:

$templateCache.put('template.html', '<h1>My template</h1>');

Or get it from the server if it's not inline:

$http.get('template.html', {cache:$templateCache});

like image 163
Mohammad Sepahvand Avatar answered Sep 22 '22 23:09

Mohammad Sepahvand


To preload templates at application initialization, you can use:

angular
.module('app')
.run(['$state', '$templateCache', '$http',
    function ($state, $templateCache, $http) {
        angular.forEach($state.get(), function (state, key) {
            if (state.templateUrl !== undefined && state.preload !== false) {
                $http.get(state.templateUrl, {cache: $templateCache});
            }
        });
    }
]);

This will preload all templateUrls by default unless preload: false is set in the state definition.

Thanks to Sobieck's answer here for the concept, which I modified for use with ui-router.

like image 24
Mark Leong Avatar answered Sep 24 '22 23:09

Mark Leong