最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to load a Javascript file without Script tag? - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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);

Thanks @Fletch, my ES2015 equivalent:

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

评论列表(0)

  1. 暂无评论