0

I am trying to replace the document.write() in the section of an html file. It’s old code that I need to support. I need to insert a javascript file based upon the language code and have it loaded before the other javascript files are loaded. The other javascript files use several of its functions. How do I do that?

The html file contains:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
    <head>

myLocale is a variable that contains the language that was stored in the cookie (e.g. en_US).

Existing code:

    <script language="javascript">
      document.write( '<scr' + 'ipt src="/file1_'+myLocale+'.js"  type="text/javascript"></scr' + 'ipt>' );
    </script>

    <script src=”/file2.js” type=”text/javascript”></script>
    <script src=”/file3.js” type=”text/javascript”></script>
    <script src=”/file4.js” type=”text/javascript”></script>

…

    </head>

file1_.js is language dependent. Files 2-4 depend upon functions in file1_.js, thus the files must be loaded in order.

Because the page and the javascript files are already loaded, it doesn’t do any good to create a script element and insert/append it to the <head> section.

The following and its many variations do not work.

    <script>
        var script = document.createElement("script");
        var scriptSrc = '<scr' + 'ipt src="/file1_'+myLocale+'.js";
        script.setAttribute("src", scriptSrc);
        script.setAttribute("async", "false");
        var head = document.head;
       head.insertBefore(script, head.firstChild);
    </script>

How do I get the javascript file loaded before the others? Thank you, Jim

Barmar
  • 741,623
  • 53
  • 500
  • 612
Jim
  • 11
  • 1
  • 1
    This is a situation where `document.write()` may be the best solution. – Barmar Jul 27 '22 at 20:52
  • You can also have the language JS file load all the other JS files. There are several ways to do this described here: [How do I include a JavaScript file in another JavaScript file?](https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file) – icecub Jul 27 '22 at 20:56
  • Honestly though, if a JS file is "language specific", a more proper solution (imho) would be to just create a bunch of JSON files with all the different language strings and have a "global" JS language file use the correct JSON file for the translations. – icecub Jul 27 '22 at 21:01

1 Answers1

0

If you can update the header code, one solution is to dynamically add ALL of that javascript.

let myLocale = "en";
let files = ["file1_" + myLocale + ".js", "file2.js", "file3.js", "file4.js"];

files.forEach(function(file) {
  let s = document.createElement("script");
  s.src = file;
  s.setAttribute("async", "false")
  document.head.appendChild(s)
});
imvain2
  • 15,480
  • 1
  • 16
  • 21