4

I have a code where I have nested <script> tag, the inner script tag does nothing but loads another Javascript file using src attribute. Because, How in my code, the inner script tag is closing the outer script.

Since I am already inside JavaScript mode, is there a way to load another script without using <script src=""> call?

1
  • You can use jQuery's $.getScript method. There are other methods as well. You can refer require.js Commented Oct 10, 2015 at 10:42

2 Answers 2

10
var js = document.createElement("script");

js.type = "text/javascript";
js.src = "path_to_the_file.js";

document.body.appendChild(js);

but this is asynchronous, so you have to wait until the script is loaded to use it -

var js = document.createElement("script");

js.type = "text/javascript";
js.src = "path_to_the_file.js";

js.onload = function() {
 //Code using this script here
};

document.body.appendChild(js);
Sign up to request clarification or add additional context in comments.

Comments

3

Thanks @Fletch, my ES2015 equivalent:

document.body.appendChild(Object.assign(document.createElement('script'), {
  type: 'text/javascript',
  src: 'http://external.script.url',
  onload: () => this.onScriptLoaded()
}));

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.