简体   繁体   中英

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.

Instead of having to copy and paste these into each js file, is there a way to include them?

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
  • use module packagers like modul8

The latter techniques are probably overkill, you probally want a

<script src="global.js" />

in your html master page.

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.)

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 .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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