0

Here is a example code: I have following code at the end of html body

<script type="text/javascript">
    var js = document.createElement("script");
    js.src = "forms/dynamicForms/sampleFormController.js";
    document.body.appendChild(js);
    angular.bootstrap(document, ['MyApp']);
</script>

When I run my app, sampleFormController is not found, if I inspect body tag in Chrome, script is added as a child tag to body tag.

where as when I modify code and add timeout it works

<script type="text/javascript">
    var js = document.createElement("script");
    js.src = "forms/dynamicForms/sampleFormController.js";
    document.body.appendChild(js);
    setTimeout(myFunction, 2000);
    function myFunction() {
    angular.element(function() {
        angular.bootstrap(document, ['MyApp']);
      });
    }
</script>

Is there a way to make my first code to work without adding timeout?

1
  • requireJS would fit your requirement Commented Oct 24, 2016 at 5:35

1 Answer 1

2

You can set the onload property of the script tag to myFunction(). Refer to the MDN page on HtmlScriptElement for more information and an example similar to the modified code snippet below. Also, see it utilized in this example plunker.

Similarly, you can set the onerror property to a function for handling the case when an error occurs. And because this code is asynchronous, you could use Promises- see this example.

<script type="text/javascript">
    var js = document.createElement("script");
    js.src = "http://elliott.andrewz.org/data/sampleController.js";
    document.body.appendChild(js);
    js.onload = myFunction;
    function myFunction() {
        angular.element(function() {
            angular.bootstrap(document, ['MyApp']);
      });
    }
</script>
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.