Javascript file organization and design

后端 未结 3 1011
梦如初夏
梦如初夏 2021-02-14 07:28

Really getting into web development and in particular JS so I was wondering what were the best practices in terms of JS file organization and delegation of responsibilities. I a

相关标签:
3条回答
  • 2021-02-14 07:59

    The best way to handle multiple JavaScript files is to design them like modules. One main JavaScript file should act as a sort of bootloader which kicks off things by setting up your "namespace" (quoted since JavaScript doesn't have classes). Example:

    var myNamespace = {};
    

    In each of your modules, you extend the "namespace". This has two benefits:

    • Minimizes globals. In this case, you will have a single global.
    • Easy to mix and match (and reuse) modules, if designed correctly.

    Also see this for implementation details: https://stackoverflow.com/a/3722845/221061

    0 讨论(0)
  • 2021-02-14 08:01

    One large JS file is really not that "bad" compared to using multiple JS files.

    You can compress it on the server if your worried about band width, look into gzip or deflate.

    0 讨论(0)
  • 2021-02-14 08:11

    I would split the classes up into modular JS files, matching your domain. Use YUI compressor or other tools to compress JS files and minify them.

    0 讨论(0)
提交回复
热议问题