Coder Social home page Coder Social logo

jquery-i18n-properties / jquery-i18n-properties Goto Github PK

View Code? Open in Web Editor NEW
425.0 37.0 430.0 336 KB

lightweight jQuery plugin for providing internationalization to javascript from ‘.properties’ files

License: MIT License

Python 0.97% CSS 60.27% JavaScript 27.05% HTML 11.71%

jquery-i18n-properties's Introduction

jQuery.i18n.properties

About

jQuery.i18n.properties is a lightweight jQuery plugin for providing internationalization to javascript from ‘.properties’ files, just like in Java Resource Bundles. It loads and parses resource bundles (.properties) based on provided language and country codes (ISO-639 and ISO-3166) or language reported by browser.

Resource bundles are ‘.properties‘ files containing locale specific key-value pairs. The use of ‘.properties‘ files for translation is specially useful when sharing i18n files between Java and Javascript projects. This plugin loads the default file (eg, Messages.properties) first and then locale specific files (Messages_pt.properties, then Messages_pt_BR.properties), so that a default value is always available when there is no translation provided. Translation keys will be available to developer as javascript variables/functions (functions, if translated value contains substitutions (eg, {0}) or as a map.

This plugin was inspired on the Localisation assistance for jQuery from Keith Wood.

Latest Version

1.2.7

Features

  • Use Java standard ‘.properties‘ files for translations
  • Use standard ISO-639 for language code and ISO-3166 for country code
  • Sequential loading of resource bundles from base language to user-specified/browser-specified so there is always a default value for an untranslated string (eg: Messages.properties, Messages_pt.properties, Messages_pt_BR.properties)
  • Use browser reported language if no language was specified
  • Placeholder substitution in resource bundle strings (eg, msg_hello = Hello {0}!!)
  • Suport for namespaces in keys (eg, com.company.msgs.hello = Hello!)
  • Support for multi-line property values
  • Resource bundle keys available as Javascript vars/functions or as a map
  • Support for namespacing.

History

This project was originally created by Nuno Miguel Correia Serra Fernandes and published on Google Code. In 2014 it has been migrated to Github which is now the official repository.

Since then, other great contributors joined the project (see Credits section below).

It has been used in various projects, including the WebRTC phone JSCommunicator (see the demo there to see jquery-i18n-properties in action), some Sakai Project tools, etc.

Example

Take as an example the following .properties files:

Messages.properties:

# This line is ignored by the plugin
msg_hello = Hello
msg_world = World
msg_complex = Good morning {0}!

Messages_pt.properties:

# We only provide a translation for the 'msg_hello' key
msg_hello = Bom dia

Messages_pt_BR.properties:

# We only provide a translation for the 'msg_hello' key
msg_hello = Olá

Now, suppose these files are located on the bundle/ folder. One can invoke the plugin like below:

// This will initialize the plugin 
// and show two dialog boxes: one with the text "Olá World"
// and other with the text "Good morning John!" 
jQuery.i18n.properties({
    name:'Messages', 
    path:'bundle/', 
    mode:'both',
    language:'pt_BR',
    async: true,
    callback: function() {
        // We specified mode: 'both' so translated values will be
        // available as JS vars/functions and as a map

        // Accessing a simple value through the map
        jQuery.i18n.prop('msg_hello');
        // Accessing a value with placeholders through the map
        jQuery.i18n.prop('msg_complex', 'John');

        // Accessing a simple value through a JS variable
        alert(msg_hello +' '+ msg_world);
        // Accessing a value with placeholders through a JS function
        alert(msg_complex('John'));
    }
});

This will initialize the plugin (loading bundle files and parsing them) and show a dialog box with the text “Olá World” and other with “Good morning John!”. The english word “World” is shown because we didn’t provide a translation for the msg_world key. Also notice that keys are available as a map and also as javascript variables (for simple strings) and javascript functions (for strings with placeholders for substitution).

Asynchronous Language File Loading

Synchronous Ajax has now been deprecated and will be removed at some point in the future, so web developers need to start thinking about writing their code as callbacks (https://xhr.spec.whatwg.org/).

With this in mind ...

If you supply the flag 'async' on the settings and set it to true, all ajax calls are executed asynchronously and the supplied callback is called after the language files have all been downloaded and parsed. If you leave the flag off, or set it to false, the behaviour is as before: all the files are parsed synchronously and the callback is called at the end of the process.

Usage

Using the plugin

  1. Include it on your <head> section:
<script type="text/javascript" language="JavaScript"
  src="js/jquery.i18n.properties-min.js"></script>
  1. Initialize the plugin (minimal usage, will use language reported by browser), and access a translated value (assuming a key named ‘org.somekey‘ exists, it will be setup as a variable you can use directly in your Javascript):
<script>
	jQuery.i18n.properties({
  		name: 'Messages', 
  		callback: function(){ alert( org.somekey ); }
	});
</script>

Additional requirement on Firefox

If using Firefox and a Tomcat webapp, you may get a syntax error in the Javascript console. The solution is to tell Tomcat the properties files should be interpreted as text/plain. To do this, add the following to your web.xml: <mime-mapping> <extension>properties</extension> <mime-type>text/plain</mime-type> </mime-mapping>

Building a minified JavaScript file

  1. Install the closure compiler tool:

    apt-get update && apt-get install closure-compiler

  2. Run it:

    closure-compiler --js jquery.i18n.properties.js \ --js_output_file jquery.i18n.properties.min.js

Options

Option Description Notes
name Partial name (or names) of files representing resource bundles (eg, ‘Messages’ or ['Msg1','Msg2']). Defaults to 'Messages' Optional String or String[]
language ISO-639 Language code and, optionally, ISO-3166 country code (eg, ‘en’, ‘en_US’, ‘pt_BR’). If not specified, language reported by the browser will be used instead. Optional String
path Path to directory that contains ‘.properties‘ files to load. Optional String
namespace The namespace that you want your keys to be stored under. You'd access these keys like this: $.i18n.map[namespace][key]. Using a namespace minimises the chances of key clashes and overwrites. Optional String
mode Option to have resource bundle keys available as Javascript vars/functions OR as a map. The ‘map’ option is mandatory if your bundle keys contain Javascript Reserved Words. Possible options: ‘vars’ (default), ‘map’ or ‘both’. Optional String
debug Option to turn on console debug statement. Possible options: true or false. Optional boolean
cache Whether bundles should be cached by the browser, or forcibly reloaded on each page load. Defaults to false (i.e. forcibly reloaded). Optional boolean
encoding The encoding to request for bundles. Property file resource bundles are specified to be in ISO-8859-1 format. Defaults to UTF-8 for backward compatibility. Optional String
callback Callback function to be called uppon script execution completion. Optional function()

Copyright, Credits and License

Copyright © 2011 Nuno Miguel Correia Serra Fernandes (nunogrilo.com)

Special thanks to great contributors:

Licensed under the MIT License.

jquery-i18n-properties's People

Contributors

adrianfish avatar andrussuitsu avatar bootssir avatar dpocock avatar ggerbaud avatar juanjmerono avatar kasama avatar miguelwicht avatar mlohbihler avatar nfgrilo avatar pallxk avatar phish108 avatar steveswinsburg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-i18n-properties's Issues

Uncaught ReferenceError: settings is not defined

Hi!

I put my language properties file under resources/bundle/Messages_**.properties

I imported the plugin:

<!-- Internacionalização --> <script src="resources/js/jquery.i18n.properties.min.js" type="text/javascript"></script>

and loaded in my .js file:

$(document).ready(function() { jQuery.i18n.properties({ name: 'Messages', path: 'resources/bundle/', mode: 'both', language: 'en', async: true, callback: function() { console.info('Iniciando internacionalização'); $('[data-i18n]').each(function(e) { var tagName = $(this).get(0).tagName; switch (tagName) { case "A": $(this).html(jQuery.i18n.prop($(this).attr("data-i18n"))); break; } }); } }); });

but I`m getting the following error:

jquery.i18n.properties.min.js:9 Uncaught ReferenceError: settings is not defined
at Object.h.i18n.prop (jquery.i18n.properties.min.js:9)
at HTMLAnchorElement. (default.js:35)
at Function.each (jquery.min.js:2)
at n.fn.init.each (jquery.min.js:2)
at Object.callback (default.js:31)
at v (jquery.i18n.properties.min.js:1)
at n (jquery.i18n.properties.min.js:1)
at jquery.i18n.properties.min.js:1
at Object.success (jquery.i18n.properties.min.js:2)
at i (jquery.min.js:2)

what am I doing wrong?

Browser language detection is broken in newer versions of Google Chrome

In GC 44.0.2403.130 (64-bit) (on Mac OS), navigator.language is reports en-US regardless of whether I have specified a different language in the browser settings. (I have specified Spanish as the first preferred language and English as the 2nd).

It happens in:

$.i18n.browserLang = function () {
  return normaliseLanguageCode(navigator.language /* Mozilla */ || navigator.userLanguage /* IE */);
};

In the Chrome JS console, I get:

> navigator.language
en-US
> navigator.languages
["es", "en-US", "en"]

Anyway, the plugin should use navigator.languages, not navigator.language so the languages can be loaded in the preferred order.

Async loading loads default language 50% of the time

I have two properties files, Messages.properties (english) and Messages_fr.properties.

My languages.json looks like:
{ "languages": [ "", "fr", ] }

With async: true in the initialisation, and requesting french, about 50% of the time I still get english messages. It seems to depend on the order that the properties file is loaded.

If the webserver log has:

"GET /plus.codes/i18n/Messages.properties?_=1478851360136 HTTP/1.1" 200 4048
"GET /plus.codes/i18n/Messages_fr.properties?_=1478851360137 HTTP/1.1" 200 4479

then it's all good - I can get the French text. But if the requests are ordered:

"GET /plus.codes/i18n/Messages_fr.properties?_=1478851291009 HTTP/1.1" 200 4479
"GET /plus.codes/i18n/Messages.properties?_=1478851291008 HTTP/1.1" 200 4048

Then even if the language requested is "fr" I still get the English messages.

Changing to async: false appears to fix this.

Number after dot in resources keys

Using a number in resource key to start a module, makes all next entries unreadable. Same goes for starting with '-'. Keys have same problem also when there are multiple '-' in a key part.

You can use number like:
module.field.label1 = label1
module.field.label_2 = label2
module.field.label_field_module = label3

But when using it like below, is not working. It's return first element as it should, but every next one will be returned as -> "[key]", in this example "[module.field.label.2]"
module.field.label.1 = label1
module.field.label.-bc2 = label2
module.field.label.la-fd-dfs = label3

If resolving issue is too time consuming, even simple repair, just to don't accept this key and decline single rows would be much helpful. Now you have to go through whole document fixing it line by line, becouse every mistake makes all following resources not working.

How to force load only language file?

Hi to all.

When running my loadConfig() function it really is trying to load two files from de server.

config.properties
config_.properties

my config.properties doen't exist , and give me a 404 Not Found error,

There is any way to force only one? (config_.properties)

this is my code.

function loadConfig() {

    $.i18n.properties({
        name:'config', 
        path:'properties/', 
        language:'',
        cache: true,
        mode:'both',
        callback: function(){
            console.log('properties loaded');
        }
    });
}

syntax error on properties file

I have a simple properties file that has the sole entry:

event_heading = Events for {0}

This renders correctly in the UI via the following:

jQuery.i18n.prop('event_heading', formattedDate);

However the console reports a syntax error on line 1.

Add language index file to limit languages attempted

To avoid 404s when trying to locate a language file, why not implement an index containing the implemented languages? If you just standardise on 'languages.json' under the path, it could be pulled as the first op, parsed and then unimplemented languages could just be skipped.

Dynamically load HTML contents based on translation keys

I didn't like the idea of having to edit the javascript every time I add a new key so I tried to come up with the following solution to dynamically load all HTML elements based on the translation key. Here's the HTML for a complex types with parameters.

This also allows for dynamically passing the params from the HTML and not via javascript. by using an additional <span class="param"> inside the element I want to translate

HTML

<span translate="yes" class="msg_multi_placeholder">Welcome <span class="param">Jacob</span>.  Today is <span class="param">28-12-2014</span></span>

Below is the javascript I'm using for this:
javascript

function updateSelected(translationKey) {
    var params = '';
    $('.' + translationKey + ' .param').each(function(i, param) {
        params = params + ', \'' + param.textContent + '\'';
    });
    var translationCommand = '$(\'.\'+translationKey).empty().append($.i18n.prop(translationKey'+ params + '));';
    eval(translationCommand);
}
function updateAll() {
    var keys = Object.keys(($.i18n.map));
    $.each(keys, function(i, key){
       updateSelected(key);
    });
}

messages_es.properties

msg_multi_placeholder = Bienvenido <span class="param">{0}</span>. Hoy es el <span class="param">{1}</span>

I must admit, this is not very neat. I would like to find a solution to make the property file a bit neater, a double placeholder for one parameter seems a bit much.

Using synchronous loading of properties with jquery.i18n.properties in deferred scripts fails in Firefox

If one uses a script with the defer attribute to invoke synchronous property loading with jquery-i18n-properties then it may fail in Firefox.

Ex:

<script defer src="jquery.js"></script> <script defer src="jquery.i18.properties.js"></script> <script defer src="support_file_that_invokes_jquery_i18n_and_creates_helper_functions.js"></script> <script defer src="file_uses_helper_functions.1.js"></script> <script defer src="file_uses_helper_functions.2.js"></script> <script defer src="file_uses_helper_functions.n.js"></script>

This may be fixed in future versions of Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1212696#c33

Not sure if switching to the async configuration when using deferred instead of a sync will fix the behavior but I think it might.

Add namespacing for translations

Add namespacing for translations. If you have two pieces of code on the same page using i18n properties you can get the scenario where names can clash. This doesn't happen in java as you can put i18n in packages. Currently, in this library, you need to modify your resource keys with the package hierarchy, which is a bit of a burden.

French apostrophe isn't displayed

Hello
I am using jQuery.i18n this way
jQuery.i18n.properties({
name:'Messages',
path:'...',
mode:'both',
cache:false,
language:'<%= client_language %>',
checkAvailableLanguages: true,
encoding:'UTF-8',
async: false,
callback: function() {...}
}
and I am loading a French property file, UTF-8 encoded.
The issue is that apostrophes like in "Donneur d'ordre" aren't displayed. The text appears as "Donneur dordre".
Any ideas how I could achieve a correct French display?
Thank you very much for your advice.
Klaus

async true version release.

I have same problem with this post.
#25

Trying async: true settings, but haven't clear warning.
And I inspected the code in latest 1.2.0 version.
But, in ver.1.2.0, settings.async seems to be ignored.

** ver.1.2.0 **

function loadAndParseFile(filename, settings) {
    $.ajax({
        url:        filename,
        async:      false,
        cache:      settings.cache,
        contentType:'text/plain;charset='+ settings.encoding,
        dataType:   'text',
        success:    function(data, status) {
                        parseData(data, settings.mode); 
                    }
    });
}

** latest code **

function loadAndParseFile(filename, settings) {
    $.ajax({
        url: filename,
        async: settings.async,
        cache: settings.cache,
        dataType: 'text',
        success: function (data, status) {
        parseData(data, settings.mode);
            callbackIfComplete(settings);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('Failed to download or parse ' + filename);
            callbackIfComplete(settings);
        }
    });
}

When do you release async true version.

Timing issues loading properties

Due to network/browser issues you can load and parse the property files in the worng order.
For example, in the code you first load default ".properties" file then the "_xx.properties" and finally the "_xx_YY.properties" file. But this could not be the real order and due to network issues you could load the ".properties" in the last position.
In this case you will see the page in the wrong language (the default), because the load method just overwrite the properties no matter their precedence is.

The load and parse method must check if there are other languages previously loaded to avoid concurrence issues.

Can't load properties file in .net

Hello

I'm using .net framework 4.6.2 and i can't make this work.
I can't load or parse my .properties file.
Is this working with .net mvc ? .net rooting problem ? what's the good path ? there is no example here

Memory Leak in IE11

The variable: "var cbSplit; " declared as global variable is creating a memory leak in IE11.
The page where the library is used will always leak in IE11 because the IE garbage collector will not garbage it.

In order to confirm the leak I added a temporary function cleancbSplit to nullify the cbSplit variable and the memory leak was gone.

var cbSplit;
// avoid running twice, which would break cbSplit._nativeSplit's reference to the native split
if (!cbSplit) {
cbSplit = function(str, separator, limit) {
.....................
cbSplit._nativeSplit = String.prototype.split;

window.cleancbSplit = function() {
    cbSplit = null;
}

}

index.html throws errors using the library

"Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."

is what I get every time I try to use a call with jquery-i18n-properties. I just cloned the repo and opened up the index.html file locally. Am I missing something?

Why FF throws error about jquery-i18n-properties .properties content.

Hello

I have the following structure for a Spring Web App

structure

To create a .properties files in many languages I use: essiembre/eclipse-rbe

For example message.properties contains:

id = Campo ID no puede estar vacio.

and message_en_US.properties contains:

#Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/)

id = Field ID can't be empty.

My code about jquery-i18n-properties is:

jQuery.i18n.properties({
                name: 'message',
                path: '../resources/jquery.i18n.properties/messages/',
                mode: 'both',

                callback: function() {
                    console.log(jQuery.i18n.prop('id'));
                }
            });

When I execute the code on Opera and Chrome all work fine.

But just in Firefox 43.0.2 (Mac) I can see the following:

syntaxerror

If I do click for each error syntax in the right part (blue text) I can see the following respectively.

id = Campo ID no puede estar vacio.

And

#Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/)

id = Field ID can't be empty.

I don't know why that error is arising

Some ideas?

Thanks

loading language files one by one

  1. Is there any way of language file on demand(not all languages files but only the language that the user chooses)? Because if I have 20 language files loading all will be a mess
    For changing the language is there any simple function to call with the parameter the chosen language or I am obliged to initialize every time the language changes. If there is can it support loading file one by one following the choice of the user?
  2. What is the use of name parameter in the initialization; name | Partial name (or names) of files representing resource bundles (eg, ‘Messages’ or ['Msg1','Msg2']). Defaults to 'Messages' | Optional String or String[] |

languages.json documentation

I see that the plugin attempts to load {path}/languages.json ... yet I don't see any documentation detailing what this file should be or what it should look like. Have I missed part of the documentation?

Bower support

It's possibile to install this plugin via bower?
thx

Cannot get to work unless I use async

Just started using this and am unsure how this can be useful if you have to use async to get it to work at all (without getting sync warnings). For example:

$.i18n.properties({
    path: base_url + '/js/languages/',
    mode:'map',
    language:'en_GB',
    async: false
});

alert($.i18n.prop('msg_hello'));

This doesn't work unless I set aysnc: false.

So basically this library is unusable unless all your translations you want to do are run in an asynchronous manner?

issue while loading Arabic language

I have integrated example of jquery-i18n-properties.
It's working fine for Messages.properties and Messages_es_ES.properties.
But when I tried to load arabic then it shows ?????? symbol.

I have created Messages_ar.properties file with arabic content in it. when I pass value ar to language then it shows me ????? only..

Am I missing something ?

plugin does not work if jquery is loaded again

I have a setup where multiple portlets are rendered inline into the same page. Each of these emits the jquery library as it has its own requirements.

One of these uses i18n-properties. Unless it is the last one to be rendered, the subsequent loading of jquery overwrites the i18n registration.

I end up with something like this:

<script type="text/javascript" src="/library/webjars/jquery/1.11.3/jquery.min.js"></script>
...
<script type="text/javascript" src="/library/webjars/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="/my-calendar/scripts/jquery.i18n.properties.min.js"></script>
...
<script type="text/javascript" src="/library/webjars/jquery/1.11.3/jquery.min.js"></script>

This then causes:
jQuery.i18n is undefined

If the webapp using i18n-properties is the last one to be rendered, then it works, but this is not guaranteed as it is a portal.

I am wondering if this could be resolved via namespacing the invocation of i18n-properties in the specific portlet? I currently load it like this:

$(document).ready(function() {

    jQuery.i18n.properties({
        name:'Messages', 
        path:'/my-calendar/bundle/',
        mode: 'both',
        cache: true
    });

...

Use global variable i

Suggestion:
for(i=0; i<files.length; i++) {
=>
for(var i=0; i<files.length; i++) {

Not working in fancybox

I trying use jquery-i18n-properties for multilanguage, if change language in page, succses. if open fancybox, content in fancybox, not translation, conten default

Fail with characters with a preceding backslash.

If you have a property file with:

key=sample:

You'll have "sample:" instead of "sample:" that I think is the right value.
Also if you have something like:

key=sample"

You'll have an error like this:

image

synchronous ajax request

$.ajax({
      url: indexFileUrl,
      async: false,
      cache: false,
      success: function (data, status) {
          languages = data.languages;
      }
    });

why not async?

Loading browser language translations is not always necessary.

Hello,

I can see that the plugin loads browser language translations by default.
In fact this is not always needed. The developer might want to load only translations supported by application and not by browser.

I would like to suggest additional option:
useBrowserLang. It would enable or disable browser language loading.

I am aware that when the resource is not present it will not be loaded anyway, but there is no need to hit not existing resource.

TypeError: jQuery.i18n is undefined

Hello;

I try calling

 jQuery.i18n.properties({
        name: 'Messages', 
        callback: function(){ alert( org.somekey ); }
    });

But I am getting an error : TypeError: jQuery.i18n is undefined

What I've done is :


 <script type="text/javascript" src="js/jquery.min.js"></script>
         <script type='text/javascript' src='js/jquery.i18n.properties-min.js'></script>
         <script>
             jQuery.i18n.properties({
         name:'Messages', 
                path:'bundle/', 
                mode:'both',
                checkAvailableLanguages: true,
                async: true,
                callback: function() {
                    alert(t_1);
                            //app.initialize();
                }
                });
             </script>

Where have messed up?

if any key is not found in properties file it should not throw error. Exception should be handled.

if any key is not found in properties file it should not throw error. Exception should be handled by checking 'value' before accessing this object in the plugin.

from line no 237 the below changes is required to handle the exception in jquery.i18n.properties.js

if (value && value.length === 0) {
return "";
}
if (value && value.length == 1 && typeof(value[0]) == "string") {
return value[0];
}

    var str = "";
    var len=0;
    if(value){
    	len = value.length;
    }
    for (i = 0, j = len; i < j; i++) {

Can not read property of undefined i18n

Hello all,
When I try to pass language dynamically from select dropdown list, It shows following error
Uncaught TypeError: Cannot read property 'properties' of undefined at changeLanguage
Where changeLanguage is my function as follows:
function changeLanguage(lang) { lang = lang || "en_EN"; // if no language is set, use browser default jQuery.i18n.properties({ path : 'language', mode : 'both', language: lang, name: 'Messages', callback: refresh_i18n }); }

Following is the pictures of it:
issue1
issue2

What is wrong with the code?
Please do suggest!
Thanks

Language files are loaded every time a page is load

Problem:
The language files are loaded into javascript data structures every time a page is load. This impacts performance and slows down the page load.

For example, if we are using a 300KB property file, the browser may take 300 - 400 ms to load this file. This load time is repeated for each language file loaded. In a typical case, we are fetching 3 files every time we load new page, so the total load for these 3 files can go up to 800 ms.

  1. messages.properties
  2. messages_en.properties
  3. messages_en-US.properties

I solved this issue by storing the parse language files in sessionStorage, and on every page load, it will look for and try to load $.i18n.map from sessionStorage before fetching it with $.ajax.

Only the first load will take sometime to fetch the files, but after stores the files in the sessionStorage it will take 10 -20 ms for each file.

Here's a code snippet

/** Load and parse .properties files */
function loadAndParseFile(filename, settings) {

    i18nfName = 'i18nmp'+filename;
    i18nmp = sessionStorage.getItem(i18nfName);
    if (i18nmp != null){ 
        $.i18n.map = JSON.parse(i18nmp);
        return;
    }

    $.ajax({
        url:        filename,
        async:      false,
        cache:      settings.cache,
        contentType:'text/plain;charset='+ settings.encoding,
        dataType:   'text',
        success:    function(data, status) {
            parseData(data, settings.mode); 
            sessionStorage.setItem( i18nfName, JSON.stringify($.i18n.map));
        }
    });
}

stop escaping the text

I wonder f it's possible to turn off escaping.

I want to insert a text with html tags.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.