javascript .js 文件可以“包含”另一个 .js 文件吗

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

Can .js file "include" another .js file

javascriptinclude

提问by Septiadi Agus

In PhP you can.

在 PHP 中你可以。

In html, you sort of can with <script src="...">tag

在 html 中,您可以使用<script src="...">标签

but what about if we have a .js file and we want to include another .js file. How would we do so?

但是如果我们有一个 .js 文件并且我们想要包含另一个 .js 文件呢?我们怎么做?

采纳答案by T.J. Crowder

If you mean in a browser context, not directly, but you can use a loader like at RequireJS(there are several).

如果您的意思是在浏览器上下文中,而不是直接使用,但您可以使用RequireJS 之类的加载器(有几个)。

Or to do it manually:

或者手动执行:

var script = document.createElement('script');
script.src = "/path/to/the/other/file.js";
document.getElementsByTagName('script')[0].parentNode.appendChild(script);

Note, though,that with the above the functions and such in the other file won't be available for use right away. The code above startsthe process of loading the file, but it continues asynchronously. You can use events to know that the load is complete (primarily the loadevent, but on older versions of IE you have to use onreadystatechange-- this is one reason people use loaders!).

但是请注意,对于上述功能,其他文件中的此类功能将无法立即使用。上面的代码开始加载文件的过程,但它是异步继续的。您可以使用事件来知道加载已完成(主要是load事件,但在旧版本的 IE 上您必须使用onreadystatechange——这是人们使用加载器的原因之一!)。