javascript 使用 jQuery 加载外部 js 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9441142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:41:30  来源:igfitidea点击:

Load external js file with jQuery

javascriptjqueryajax

提问by Semur Nabiev

Looked for it everywhere, and found the answer but lost. anyone knows how to load an external .js file from another js file?

到处寻找,找到了答案却迷失了。有人知道如何从另一个 js 文件加载外部 .js 文件吗?

main_lobj1.onreadystatechange = function(){     
  if (main_lobj1.readyState == 4) {if (main_lobj1.status == 200) { 
    document.getElementById("middleDiv_m").innerHTML=main_lobj1.responseText;  
  jQuery.getScript('jquery/tabs.js')        
  }
}

innerHTML works and responce text is pasted. The problem is that JS is not working in that document. jQuery.getScript should be loading that external js file, but it doesnt

innerHTML 工作并粘贴响应文本。问题是 JS 在该文档中不起作用。jQuery.getScript 应该加载该外部 js 文件,但它没有

回答by Sam T

This is the way you can do it to load an external js file to Jquery

这是将外部 js 文件加载到 Jquery 的方法

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script"
});

回答by Salvador Dali

Exactly for this reason a function $.getScript()exist in jquery. You can use it simply in this way:

正是因为这个原因,jquery 中存在一个函数$.getScript()。您可以简单地以这种方式使用它:

$.getScript("test.js", function( data, textStatus, jqxhr ) {
  // this is your callback.
});

回答by Kevin Driessen

If you call an external script you want to base your script on you may want to take note that ajax-based jquery script are asynchronous by defealt.

如果你调用一个外部脚本,你想让你的脚本基于你的脚本,你可能需要注意基于 ajax 的 jquery 脚本是异步的。

Calling an external script asynchronousily will cause the rest of the rest being executed before the external script is loaded.

异步调用外部脚本将导致在加载外部脚本之前执行其余的其余脚本。

Today I ran into the same problem which was easily being solved by making a small adition to Sam Arul Raj's post:

今天我遇到了同样的问题,通过对 Sam Arul Raj 的帖子做一个小补充,很容易解决:

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script",
  async: false
});