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?
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});
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With