1

I'm working on a large web application which is primarily driven by JavaScript on client side. 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').

Is there a similar way to connect multiple source files in JavaScript? There are many large web applications with intense use of JavaScript out there, what is the common solution?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
danijar
  • 32,406
  • 45
  • 166
  • 297
  • you can append multiple file with jquery append method – Hushme Jul 27 '13 at 09:28
  • This is too general. Some applications/websites join the relevant script files into one on the serverside, others use a serverside framework to include the relevant script files seperately on each page, others again use javascript to insert script tags as needed etc. It all depends on what you need. – adeneo Jul 27 '13 at 09:32

3 Answers3

2

RequireJS is a popular solution to this requirement.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • A suggested edit (http://stackoverflow.com/review/suggested-edits/2598278) refers this link: http://stackoverflow.com/questions/11674824/how-to-use-requirejs-build-profile-r-js-in-a-multi-page-project – AKS Jul 27 '13 at 09:38
  • And most popular libraries now are either AMD "compliant", or are compatible with at least requirejs's shim functionality. – Stephen Jul 27 '13 at 10:00
1

You could have a "includer.js" that will do nothing but include other JS files, like this:

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

<script src="includer.js"></script>
tckmn
  • 57,719
  • 27
  • 114
  • 156
0

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)

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

It works for non-java app projects too.

Damon Smith
  • 1,770
  • 18
  • 24