0

I am trying to dynamically add an external script tag to my html as follows:

html

<html>
        <head>
                <script src="js/load-scripts.js"></script>
        </head>
        <body>
            <form>
                Load scripts NOW!!<br/>
                <input type="text" onclick="downScripts(); testCall();" value="Click to Load scripts and test" />
            </form>
        </body>
    </html>

load-scripts.js

function downScripts() {
    var element = document.createElement("SCRIPT");
    element.src = "js/try-catch.js";
    element.defer = false;
    console.log(element);
    document.body.appendChild(element);
 }

When I click on the button, the js/try-catch.js file gets added to the Sources in chrome dev tools, but when I try to call one function from try-catch.js - which is defined in try-catch.js (like testCall() below)

try-catch.js

function testCall() {
    alert('scripts imported from try catch js external');
}

If the external javascript has been added (i see it in developer tools), why am i not able to call one of it's functions- I get this error: Uncaught ReferenceError: testCall is not defined

5
  • You need to use event delegation method... Commented Feb 13, 2015 at 9:19
  • do i have to use .delegate() method in jquery?? Commented Feb 13, 2015 at 9:27
  • I mean instead of onclick attribute use addEventListener.... and obviously you can do it with jquery method too @Prabhas... Commented Feb 13, 2015 at 9:28
  • I think your external javascript doesn't load properly. First answer for this question can help you: stackoverflow.com/questions/14897849/… Commented Feb 13, 2015 at 9:30
  • Why don't you just use SystemJs or likes? Commented Feb 13, 2015 at 9:45

1 Answer 1

0

The testCall function is called earlier than try-catch.js is loaded.

Sign up to request clarification or add additional context in comments.

Comments

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.