0

I'm trying to make my website load different js files based on users languages. Possible?

I got this javascript application: test.js <- inside this i can define the language (default eng)

So that, i would like to recreate test.js and name it like test-it.js test-es.js ecc.

In my index the script is loaded as usual:

<script type="text/javascript" src="http://mysite.com/test.js"></script>

Is it possible to setup an if/else condition that detect browser language and load the right js app?

Thanks, Gio

iGio90
  • 3,251
  • 7
  • 30
  • 43
  • 1
    Geographic IP localisation > Yes it's possible, but possible to spoof. – Charles Forest Jun 17 '13 at 18:34
  • Yes it is possible, but why would you do this rather than instead storing the localization data in a separate file? – Kevin B Jun 17 '13 at 18:35
  • 1
    [Server-side language selection](http://www.w3.org/International/questions/qa-apache-lang-neg) is the oldest and best approach. (Don't go by location; that tells you nothing about the user's preferred language.) – Blazemonger Jun 17 '13 at 18:36
  • Maybe take a look at: http://stackoverflow.com/questions/1043339/javascript-for-detecting-browser-language-preference – kyle.stearns Jun 17 '13 at 18:47
  • Ask the user his preferred language? and then do what changes you need to, just an alternative approach. Always better to *not assume* things – painotpi Jun 17 '13 at 19:06

1 Answers1

0

Browsers will typically send an Accept-Language HTTP header indicating the user's preferred language.

In php you can read this header and use it to return the appropriate file.

test.php

<?php
$locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
list($language, $country) = explode('_', $locale);
include 'test-'.$language'.js';
?>

This however is not the best approach, because you may want to give the user the ability to override the language and not use the browser's language. Also, the browser may not send a language at all, or it may specify a language you do not support. Also, using server side selection like this may hurt your ability to cache the file. Also, if the JavaScript file has code in it besides language you do not want to duplicate the code in multiple files.

I would recommend using a library for this like: http://i18next.com/

Adam
  • 43,763
  • 16
  • 104
  • 144