简体   繁体   English

在Javascript中包含模块的正确方法是什么?

[英]What is the proper way to include modules in Javascript?

I am using quite a bit of javascript in which it would be rather helpful if I could use global constants and a few methods that I use all over my web site. 我使用了大量的javascript,如果我可以使用全局常量和在整个网站上使用的一些方法,这将非常有帮助。

Instead of having to copy and paste these into each js file, is there a way to include them? 不必将它们复制并粘贴到每个js文件中,有没有办法包含它们?

like: 喜欢:

#include global.js

jsCode

There are multiple techniques for module architecture 模块架构有多种技术

  • include multiple script tags and use namespaces to avoid global scope issues 包括多个脚本标记并使用名称空间来避免全局范围问题
  • use asynchronous file loaders like requireJS 使用诸如requireJS之类的异步文件加载
  • use module packagers like modul8 使用像modul8这样的模块打包

The latter techniques are probably overkill, you probally want a 后面的技术可能是过大的,您可能想要

<script src="global.js" />

in your html master page. 在您的html主页中。

Unfortunately, there's no standard JavaScript way to include one JavaScript file into another JavaScript file (I believe this is one of those lovely JavaScript's peculiarities.) 不幸的是,没有标准的 JavaScript方法将一个JavaScript文件包含到另一个JavaScript文件中(我相信这是那些可爱的JavaScript的特点之一。)

But, before you start to choose work-around, note that it's often considered a good practice to merge JavaScript files all over the project into a single big file (in short, this technique reduces number of HTTP requests and improves performance, for more explanations and caveats see Merging multiple javascript files .) 但是,在开始选择解决方法之前,请注意,通常将整个项目中的JavaScript文件合并为一个大文件被认为是一种好习惯(简而言之,此技术可减少HTTP请求的数量并提高性能,有关更多说明,和注意事项请参阅合并多个javascript文件 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM