'Read array value from a variable inside an HTML head [duplicate]

This is the HTML structure...

<head>
...
  <script>
     ENV = {...,
         current_user: {
            id: "314",
            display_name: "My name"
                       }
           } 
  <script/>
...
<head/>

I'm trying to read "display_name" to use in another part of the application.

If I press F12 and run the below in the console it works returning the name:

console.log(ENV.current_user.display_name)

but below doesn't work inside same page of the above:

<script>
    const x = ENV.current_user.display_name;
    
    document.getElementById("std").innerHTML = x;
</script>
<h3 id="std"></h3>

How can I print "My name" inside this h3?



Solution 1:[1]

you can import in all pages a global configuration file (config.js) and then include others scripts

<body>
 <h3 id="std"></h3>
 <script src="config.js" />
 <script>
     const x = ENV.current_user.display_name;
    
     document.getElementById("std").innerHTML = x;
 </script>
</body>

and your config file would have the ENV variable.

the scripts should not be declared in the header for reasons of page load time, it is always recommended to place them at the end inside the body tag

Solution 2:[2]

Your std element isn't rendered yet when your script is running. This should work:

<script>
    (function() {
          const x = ENV.current_user.display_name;
          document.getElementById("std").innerHTML = x;
     })();
</script>

Put it in the body, at the end of the body.

Solution 3:[3]

Your

document.getElementById("std").innerHTML = x;

doesn't work because your script run before the DOM finished loading, so they will return null or undefined. What you can do is to put your at the end of <body></body>

Here is the what the entire code should look like:

<head>
    <script>
        ENV = {
            current_user: {
                id: "314",
                display_name: "My name"
            }
        } 
    </script>

</head>
<body>
    <h3 id="std"></h3>

    <script>
        const x = ENV.current_user.display_name;
        document.getElementById("std").innerHTML = x;
    </script>
</body>

Another way to make sure that your browser run the script after HTML is loaded is by separate the js script to different a file and include it in HTML by

<script defer src='./filename.js'></script>

The word defer tell the browser to run filename.js only when the HTML is loaded.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nelsongt77
Solution 2 JoeKincognito
Solution 3 Sokmontrey