Load JavaScript based on user language

Hello there ! hope you’re doing well.
I’m using a JS plugin to translate pages of my website.
The script translates pages onload to french, what I want is for the script to translate based on the country, more specifically, I want the script to be able to translate to French for users from France and to English for all other users. I’ve seen a good post on SO about using navigator.languages using the following code:

var userLang = navigator.language || navigator.userLanguage; 
alert ("The language is: " + userLang);
</script>

Instead of firing an alert with the user language, I need it to load javascript files if the user’s language is French or visiting from France.

I hope I can get some help.

Thanks !

Hi well there are some ways you can do this. based on a stack overflow answer
you could do this

`

var loadJS = function(url, implementationCode, location){
    //url is URL of external file, implementationCode is the code
    //to be called from the file, location is the location to 
    //insert the <script> element

    var scriptTag = document.createElement('script');
    scriptTag.src = url;

    scriptTag.onload = implementationCode;
    scriptTag.onreadystatechange = implementationCode;

    location.appendChild(scriptTag);
};
var yourCodeToBeCalled = function(){
//your code goes here
}
loadJS('yourcode.js', yourCodeToBeCalled, document.body);

you can find the full stack overflow thread here:

But i recommend instead to use a library like polyglot.js or something similar that uses translation objects to fill your HTML page
`

Pretty much a lot for a simple thing, here’s what worked for me:

if (navigator.language == 'fr') { 
   let s = document.createElement('script'); 
   s.src='url'; 
   document.head.appendChild(s); 
}

Thanks anyways !

Also I think you didn’t fully read my question, I’m trying to load JavaScript conditionally based on user’s browser language.

ah yeah, i did haha. but you already had the language part figured out. so i just gave you the snippet to load js dynamically. glad you could resolve the problem tho!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.