0

I have two files. An HTML file:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
function update_layout()
{
    var new_source = document.createElement('script')
    new_source.src = 'script_code.js'
    new_source.type = 'text/javascript'
    document.getElementsByTagName('head')[0].appendChild(new_source)
}
function do_layout()
{
    alert(Lay_Table['nam'])
}
        </script>
    </head>
    <body>
        <input type="button" value="Update" onclick="update_layout();do_layout();"/>
    </body>
</html>

and an JavaScript file named "script_code.js":

Lay_Table = {}
Lay_Table['nam'] = 'US 104 Key'

When I click on the "Update" button I get an error instead of an alert containing the text "US 104 Key".

I have looked at very similar questions on Stack Overflow but cannot find out what is wrong. Have I made a mistake, or is this method no longer allowed due to security reasons? I am using Google Chrome.

posfan12
  • 2,541
  • 8
  • 35
  • 57

1 Answers1

2

The script takes a bit of time to get inserted into the document and run - it doesn't happen immediately, so the Lay_Table is not defined in time when do_layout runs. Consider adding a load listener to the inserted tag (and avoid inline handlers, they have way too many problems to be worth using nowadays, such as a demented scope chain and quote escaping issues):

window.addEventListener('DOMContentLoaded', () => {
  document.querySelector('input').addEventListener('click', update_layout);
});
function update_layout()
{
    var new_source = document.createElement('script')
    new_source.src = 'script_code.js'
    new_source.addEventListener('load', do_layout);
    document.head.appendChild(new_source)
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320