简体   繁体   中英

How to switch between 2 javascript files

I just wonder if it possible to change/ switch between 2 javascript files in a web page ? If user choose the EN language from my site then the file alljavaforEN.js will be activated. But If user choose the FR language from my site then the file alljavaforFR.js will be activated

I´m so sorry if my question is too simple. But I have been search in google I have not found any tutrials. Possibly I use wrong keywords ?

However what I did here is

<html>
<head>

Function changeLanguage (lang) {
if (lang=="fr"){///Do something to activate this <script type="text/javascript" src="alljavaforFR.js"></script>}

if (lang=="en"){ //Do something to activate this <script type="text/javascript" src="alljavaforEN.js"></script>}

}
</head>
<body>
  <a href="#" onclick="changeLanguage('en');"> Change to English</a>
  <a href="#" onclick="changeLanguage('fr');"> Change to French</a>
</body>
</html>

This is kind of ugly... but.

if (lang=="fr"){
    document.write('<script type="text/javascript" src="alljavaforFR.js"></script>')
}

if (lang=="en"){ 
    document.write('<script type="text/javascript" src="alljavaforEN.js"></script>')
}

Alternatively a better approach might be (not when the page is loading) to load the script in a deferred way, something like.

function loadScript(src){
    var el = document.createElement("script");
    el.src = src;
    document.body.appendChild(el);
}

And then:

if (lang === "fr"){
    loadScript("alljavaforFR.js")
} else  if (lang === "en"){
    loadScript("alljavaforEN.js");
}

(You can wrap it in a function)

try this:

<script type="text/javascript" id="script" src="alljavaforFR.js"></script>

<script type="text/javascript">
function changeLanguage(lang) {
  var src;
  switch(lang) {
    case "en":
    src = "alljavaforEN.js";
    break;
    case "fr":
    default:
    src = "alljavaforFR.js";
  }
  document.getElementById("script").src = src;
}
</script>


<a href="#" onclick="changeLanguage('en');"> Change to English</a>
<a href="#" onclick="changeLanguage('fr');"> Change to French</a>

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