可以.js文件“包含”另一个.js文件 [英] Can .js file "include" another .js file

查看:104
本文介绍了可以.js文件“包含”另一个.js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PhP中,你可以。

在html中,您可以使用< script src =...> tag

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

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

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

推荐答案

如果你的意思是在浏览器环境中,而不是直接 ,您可以使用像 RequireJS 这样的加载程序(有几个)。

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

或者手动完成:

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

但是请注意,上面的函数和其他文件中的函数将不可用立即使用。上面的代码启动加载文件的过程,但它会异步地继续。您可以使用事件来了解负载是否完整(主要是加载事件,但在旧版本的IE上,您必须使用 onreadystatechange - 这是人们使用装载机的一个原因!)。

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 starts the process of loading the file, but it continues asynchronously. You can use events to know that the load is complete (primarily the load event, but on older versions of IE you have to use onreadystatechange -- this is one reason people use loaders!).

这篇关于可以.js文件“包含”另一个.js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆