I am trying to replace the document.write() in the <head> section of an html file

221 Views Asked by At

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

1

There are 1 best solutions below

0
imvain2 On

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)
});