Put JavaScript in One .Js File or Break It Out into Multiple .Js Files

Should I split my javascript into multiple files?

There are lots of correct answers, here, depending on the size of your application and whom you're delivering it to (by whom, I mean intended devices, et cetera), and how much work you can do server-side to ensure that you're targeting the correct devices (this is still a long way from 100% viable for most non-enterprise mortals).

When building your application, "classes" can reside in their own files, happily.

When splitting an application across files, or when dealing with classes with constructors that assume too much (like instantiating other classes), circular-references or dead-end references ARE a large concern.

There are multiple patterns to deal with this, but the best one, of course is to make your app with DI/IoC in mind, so that circular-references don't happen.

You can also look into require.js or other dependency-loaders. How intricate you need to get is a function of how large your application is, and how private you would like everything to be.

When serving your application, the baseline for serving JS is to concatenate all of the scripts you need (in the correct order, if you're going to instantiate stuff which assumes other stuff exists), and serve them as one file at the bottom of the page.

But that's baseline.

Other methods might include "lazy/deferred" loading.

Load all of the stuff that you need to get the page working up-front.

Meanwhile, if you have applets or widgets which don't need 100% of their functionality on page-load, and in fact, they require user-interaction, or require a time-delay before doing anything, then make loading the scripts for those widgets a deferred event. Load a script for a tabbed widget at the point where the user hits mousedown on the tab. Now you've only loaded the scripts that you need, and only when needed, and nobody will really notice the tiny lag in downloading.

Compare this to people trying to stuff 40,000 line applications in one file.

Only one HTTP request, and only one download, but the parsing/compiling time now becomes a noticeable fraction of a second.

Of course, lazy-loading is not an excuse for leaving every class in its own file.

At that point, you should be packing them together into modules, and serving the file which will run that whole widget/applet/whatever (unless there are other logical places, where functionality isn't needed until later, and it's hidden behind further interactions).

You could also put the loading of these modules on a timer.

Load the baseline application stuff up-front (again at the bottom of the page, in one file), and then set a timeout for a half-second or so, and load other JS files.

You're now not getting in the way of the page's operation, or of the user's ability to move around. This, of course is the most important part.

Is it better to split JavaScript into multiple files, or have it all in one file?

It depends on the size of your Javascript and the data connection of the user, as well as the (non-)use of technologies such as HTTP2.

In general the answer is that combining separate Javascript files into a single file per page is better for performance. There's nothing to say you couldn't do this separately for each of your pages, meaning you'd have a single Javascript file with the page-specific functions, as well as the common functions you've described. You can do that manually, or use a tool like gulp to perform the task automatically.

All code in one js file vs separating code into multiple js files

There are a number of options here, focused purely on the side of organizing your files it's worth considering using a library like require.js if what you're working on is fairly big. This however is meant for applications and even though you can easily use it for other things as well the idea is that you restructure your code into stand alone modules which might or might not be sensible in your case.

If however the javascript we're talking about is tightly coupled with the content of the page and thus in it's very setup not reusable for other pages it can be quite correct to use inline <script> tags rather than external javascript files.

And one last note, require.js or any setup with multiple javascript will give a slight overhead regarding http requests, but I would not worry about that too much. Require.js or similar libraries will even load this async for you, so all in all it will probably be a bit more efficient than one huge file which possibly isn't used for a big part for any given visitor (though that depends whether visitors will in the end visit all pages or not).

One big javascript file or multiple smaller files?

It is generally a good idea to have fewer HTTP requests. So you should reduce the number of files as much as is reasonable.

My personal preference is to have three "groups" of JavaScript files:

  1. Core file. Contains functions that are used almost everywhere and other useful page initialisation things.
  2. Module files. Contains code that is used in several places, but not everywhere. Can be dropped in to provide additional functionality. For instance, if you have a script to handle date inputs, you could include it as a module file and add it to pages that have date inputs.
  3. Page-specific files. These files contain code that is only used in one place. The only reason they're added as separate files than as part of the page itself is for cache reasons.

How can I split a javascript application into multiple files?

Take a look at the design pattern in this article: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth - you can split your module definition across multiple files in a way that lets common properties be shared but also lets you create variables or methods that are private just to a particular file.

The basic idea is that the individual JS files add to the same module with code like this:

var MODULE = (function (my) {
var privateToThisFile = "something";

// add capabilities...

my.publicProperty = "something";

return my;
}(MODULE || {}));

Where in each JS file if MODULE is already defined (from another JS file) you add to it otherwise you create it. You can set it up so that it (mostly) doesn't matter what order the various files are included in.

The article details several variations, and of course you'll probably come up with your own tweaks...

Can you use multiple .JS files when developing a complex Javascript application?

There two possible ways.
Personally, I would use a build tool to simplify working with multiple files.

Using a build tool

Grunt

My favourite tool to keep up with complex js applications is grunt. With grunt you can develop in as many files as you want and use its plugins watch and concat to automatically concat them on save. You can do a lot more but this is the basic use case which may be helpful for you.

Grunt requires nodejs and takes some time to setup. But once you are ready with your Gruntfile setup it really speeds up your development process.

To make your project ready for production use you can also minify your scripts with some configuration and a single command.

A lot of the major javascript libraries are using grunt, easily recognizable based on their Gruntfile: jQuery, AngularJS, Twitter Bootstrap etc.

Grunt is also part of the development toolset yeoman.

Brunch

Brunch is another build tool which allows you to do similar things like grunt does.

Loading only the needed files

If you are developing a huge single page application and are concerned about the startup time of your application, one single file may not be the best solution. In this case you can use a javascript module loader.

Require.js

Therefor require.js is a goot fit. It allows you to only load the actual needed files on the current page. Though setting up require.js is a bit more work than setting up grunt.

How can I split my javascript code into separate files?

You should have one global namespacing object which every module has to access and write to. Modify your files like so:

// employe.js

window.myNameSpace = window.myNameSpace || { };

myNameSpace.Employee = function() {
this.name = "";
this.dept = "general";
};

and Manager.js could look like

// Manager.js

window.myNameSpace = window.myNameSpace || { };

myNameSpace.Manager = function() {
this.reports = [];
}
myNameSpace.Manager.prototype = new myNameSpace.Employee;

This is of course a very simplified example. Because the order of loading files and dependencies is not child-play. There are some good librarys and patterns available, I recommend you looking at requireJS and AMD or CommonJS module patterns. http://requirejs.org/



Related Topics



Leave a reply



Submit