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.

1 Answer 1

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)
}
Sign up to request clarification or add additional context in comments.

3 Comments

I need to run the do_layout function too. When I do I get the same error as before.
The new_source.addEventListener('load', do_layout); should run it only after the inserted script has loded.
Question: What do I do if I have more than one script that needs to load? Thanks.

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.