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?
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?
Share Improve this question asked Oct 10, 2015 at 10:34 Javin PaulJavin Paul 451 gold badge1 silver badge4 bronze badges 1- You can use jQuery's $.getScript method. There are other methods as well. You can refer require.js – Rajesh Commented Oct 10, 2015 at 10:42
2 Answers
Reset to default 10var 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);
Thanks @Fletch, my ES2015 equivalent:
document.body.appendChild(Object.assign(document.createElement('script'), {
type: 'text/javascript',
src: 'http://external.script.url',
onload: () => this.onScriptLoaded()
}));