简体   繁体   English

我可以在JavaScript中包含其他源文件吗?

[英]Can I include another source file in JavaScript?

I'm working on a large web application which is primarily driven by JavaScript on client side. 我正在开发一个大型Web应用程序,主要由客户端的JavaScript驱动。 I am still in prototyping phase and I am at a point where source files become very long and I would like to split it up into multiple files. 我仍处于原型设计阶段,我处于源文件变得非常长的地步,我想将其拆分成多个文件。

For example in PHP I would just call include('source.php') or require_once('source.php') . 例如在PHP中,我只需要调用include('source.php')require_once('source.php')

Is there a similar way to connect multiple source files in JavaScript? 有没有类似的方法来连接JavaScript中的多个源文件? There are many large web applications with intense use of JavaScript out there, what is the common solution? 有很多大型Web应用程序在那里大量使用JavaScript,常见的解决方案是什么?

RequireJS是这一要求的流行解决方案。

You could have a "includer.js" that will do nothing but include other JS files, like this: 你可以有一个“includer.js”除了包含其他JS文件之外什么都不做,比如:

includer.js includer.js

var files = ['someScript', 'anotherScript', 'moreScript']
for (var i = 0; i < files.length; i ++) {
    var scriptEl = document.createElement('script')
    scriptEl.src = files[i] + '.js'
    document.head.appendChild(scriptEl)
}

HTML HTML

<script src="includer.js"></script>

I wrote a tool in Java specifically designed to manage large javascript codebases for web apps by detecting your dependencies and bundling your javascript, allowing you to just add and change files without worrying about which files to include and in what order (as long as you conform to a naming scheme and folder structure) 我编写了一个Java专用工具,专门用于管理Web应用程序的大型JavaScript代码库,通过检测您的依赖关系并捆绑您的javascript,允许您只需添加和更改文件,而无需担心要包含哪些文件以及按什么顺序(只要您符合到命名方案和文件夹结构)

http://damonsmith.github.io/js-class-loader/ http://damonsmith.github.io/js-class-loader/

It works for non-java app projects too. 它也适用于非Java应用程序项目。

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

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