rink.attendant.6
rink.attendant.6

Reputation: 46228

Loading JavaScript language packs via Modernizr

I'm faced with the issue of loading language packs for JavaScript libraries and I'm not sure what the best approach is. This is what I need to do:

  1. Load the library files (JavaScript and possibly CSS)
  2. Detect the language of the page (the lang attribute of the <html> tag is set)
  3. Load the appropriate language pack. For some libraries, a language pack is not needed for English.
  4. Initialize the plugin after the language pack is loaded (or immediately, if no language pack is necessary).

I'm trying out Modernizr and came up with this solution but it seems rather messy:

'use strict';
Modernizr.load({
    load: ['jquery.countdown.min.js', 'jquery.countdown.css'],
    complete: function() {
        switch(document.documentElement.lang) {
            case 'fr-CA':
                Modernizr.load({
                    load: 'jquery.countdown-fr.js',
                    callback: function() {
                        initCountdown();
                    }
                });
                break;
            case 'zh-CN':
                Modernizr.load({
                    load: 'jquery.countdown-zh-CN.js',
                    callback: function() {
                        initCountdown();
                    }
                });
                break;
            default:
                initCountdown();
                break;
        }
    }
});

Something else that I've tried is using the test in yepnope.js to test whether document.documentElement.lang === 'fr-CA' and so on, but I'm not sure how I can write multiple tests to load something THEN execute a callback function after ONE of the cases finish. This code seemed to work for the cases that requires a language pack (anything except English):

Modernizr.load({
    load: ['jquery.countdown.min.js', 'jquery.countdown.css'],
    complete: function() {
        Modernizr.load([
            {
                test: document.documentElement.lang === 'fr-CA',
                yep: 'jquery.countdown-fr.js',
                callback: function() {
                    initCountdown();
                }
            },
            {
                test: document.documentElement.lang === 'zh-CN',
                yep: 'jquery.countdown-zh-CN.js',
                callback: function() {
                    initCountdown();
                }
            }
        ]);
    }
});

If it was just two languages then I could easily test for one and load it in either yep or nope, but ideally I'd like to support more than two languages.

Ideas anyone?

I will note here that I have looked at this question: Execute callback after modernizr/yepnope has loaded all files

Upvotes: 2

Views: 643

Answers (0)

Related Questions