Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a Javascript file without Script tag?

Tags:

javascript

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?

like image 249
Javin Paul Avatar asked Sep 17 '25 10:09

Javin Paul


2 Answers

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);
like image 200
Fletch Avatar answered Sep 19 '25 23:09

Fletch


Thanks @Fletch, my ES2015 equivalent:

document.body.appendChild(Object.assign(document.createElement('script'), {
  type: 'text/javascript',
  src: 'http://external.script.url',
  onload: () => this.onScriptLoaded()
}));
like image 37
Stephen Paul Avatar answered Sep 20 '25 00:09

Stephen Paul