jQuery 在另一个js文件中加载外部js文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18261214/
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-08-26 21:17:14  来源:igfitidea点击:

Load external js file in another js file

javascriptjquery

提问by Gaurav

I have this file include in my html and I want to call it from another javascript. Please suggest me how should I do it?

我有这个文件包含在我的 html 中,我想从另一个 javascript 调用它。请建议我该怎么做?

<script type="text/javascript" src="js.js">/*
  old:123
  new: 456*/
</script>

I want to include it in my js file, not in the html.

我想将它包含在我的 js 文件中,而不是包含在 html 中。

回答by doitlikejustin

If you want to include a JS file in a JS you can use jQuery.getScript()for that

如果你想在一个JS,你可以使用一个JS文件jQuery.getScript()

$.getScript('another_file.js', function() {
    //script is loaded and executed put your dependent JS here
});

And if you cannot use jQuery

如果你不能使用 jQuery

var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.head.appendChild(imported);

Source

来源

For more information about the current CSP3 spec from W3 look here.

有关 W3 当前 CSP3 规范的更多信息,请查看此处