简体   繁体   中英

Load different JS based on users location

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM