user3632710 user3632710 - 1 month ago 28
AngularJS Question

How to fix angular-translate FOUC issues while using translatePartialLoader?

I've been experiencing FOUC (flash of untranslated content) issues while using angular-translate. This is my setup:

.config(function ($translateProvider, defaultI18n) {
$translateProvider
.useSanitizeValueStrategy('sanitize')
.translations('en-GB', defaultI18n.en)
.useCookieStorage()
.useLoader('$translatePartialLoader', {
urlTemplate: '/{part}/{lang}.json'
})
.preferredLanguage('en-GB')
.fallbackLanguage('en-GB');
})
.run(function ($rootScope, $translate) {
$rootScope.$on('$translatePartialLoaderStructureChanged', function () {
$translate.refresh();
});


Since I'm using
$translatePartialLoader
in each controller view I have:

.controller('SomeController', function ($translatePartialLoader) {
$translatePartialLoader.addPart('path-to-some-view-i18n');
})


If I remove
$translate.refresh()
FOUC goes away, but the text isn't updated with the new locale. Not sure if having text in my HTML files maybe causing a conflict here.

How can I remove FOUC completely but still keeping the app translating correctly?

Should I remove all text from my HTML files?

Thanks in advance.

Answer

I changed the logic a bit and the FOUC issues seem to disappear. Instead of executing $translatePartialLoader.addPart('path-to-some-view-i18n'); in each controller, I defined for each state the respective i18n route(s) like this:

.state('state1', {
    url: '/state1',
    templateUrl: 'path-to-some-view',
    data: {
        i18n: ['path-to-some-view-i18n']
    }
})

And then, when the event $stateChangeStart is triggered:

.run(function ($rootScope, $translate, $translatePartialLoader) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        if(toState.data.i18n) {
            angular.forEach(toState.data.i18n, function (value) {
                $translatePartialLoader.addPart(value);
            });
        }
    });

    $rootScope.$on('$translatePartialLoaderStructureChanged', function () {
        $translate.refresh();
    });
});
Comments