2

Can I use Javascript to load a Javascript file in HTML based on a string in URL? For example something like this:

<script type="text/javascript">
if (location.href.indexOf("DEUTCH") != -1) 
    {
    include ('javascript_deutch.js)
    }
    else 
    {
    include ('javascript_english.js)
    }
</script>

I cannot use any other method like PHP or something.


Thanks for the help guys. Unfortunately none of these things seem to work.

This

<script type="text/javascript">
if (location.href.indexOf("DEUTCH") != -1) {
   document.head.innerHTML+='<script src="javascript_deutch.js"></script>';
}else{
   document.head.innerHTML+='<script src="javascript_english.js"></script>';
}
</script>

ended up just displaying a message at the top of my page:

'; }else{ document.head.innerHTML+=''; } 

And this

<script type="text/javascript">
var script = document.createElement('script');
if (location.path.indexOf("DEUTCH") > -1) {
script.src = 'javascript_deutch.js';
} else {
script.src = 'javascript_english.js';
}
document.body.appendChild(script);
</script>

did not request the files on the server at all. Am I missing something?

1
  • As for the error in caused by my answer; I've edited it. Commented Nov 24, 2015 at 15:04

4 Answers 4

1

You can create a <script> tag dynamically:

var script = document.createElement('script');
if (location.path.indexOf("DEUTCH") > -1) {
  script.src = 'javascript_deutch.js';
} else {
  script.src = 'javascript_english.js';
}
document.body.appendChild(script);
Sign up to request clarification or add additional context in comments.

Comments

1

The easy way without framework:

var _script = document.createElement('script');
_script.src = 'fileName.js';
document.body.appendChild(_script);

May be will be good to isolate this into separate function like this:

function includeJsFile(fileName) {
     var _script = document.createElement('script');
    _script.src = fileName;
    document.body.appendChild(_script);
}

But may be will be good for you to check http://requirejs.org/

Comments

0

Why not. Just add them in the script tags.

<script type="text/javascript">
if (location.href.indexOf("DEUTCH") != -1) {
   document.head.innerHTML+='&lt;script src="javascript_deutch.js"&gt;&lt;/script&gt;';
}else{
   document.head.innerHTML+='<&lt;script src="javascript_english.js"&gt;&lt;/script&gt;';
}
</script>

Comments

0

Try this code, this method worked for me:

<script>
document.write('<script type="text/javascript" src="' + language-file + '.js"><\/script>')
</script>    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.