Referencing separate JS files vs one JS file - javascript

Which would result in greater speed/efficiency: Referencing one JavaScript file for all files in the directory OR referencing a different JavaScript file for each file in the directory?
So basically, referencing the same JavaScript file in all web pages vs a unique JavaScript file for every webpage.
Note: I thought that referencing the single file would be slower as there is code in there that is obsolete to some files, thus running useless code and causing the file to run less efficient.

There are tradeoffs involved so you may ultimately need to measure your specific circumstances to be sure. But, I'll explain some of the tradeoffs.
If you have giant amounts of data or giant amounts of code that are only used in one or a few pages, then you will probably want to separate that out into its own file just so you can ONLY load it, initialize it and have it take memory when it's actually needed. But, note with the amount of memory in modern computers (even phones these days), the data or code has to be pretty large to warrant a separate download.
Other than item 1, you pretty much always want to optimize for maximum caching efficiency. Retrieving a file (even a larger file than needed) from the cache is so massively much faster than retrieving any file (even a small file) over the network that you really want to optimize for caching. And, the time to retrieve these files generally dwarfs any of the JS parse time (CPUs are pretty fast these days) so triggering an extra download to save some JS parse time is unlikely to be faster.
The best way to optimize for caching is to have most of your pages reference the same common script files. Then, they get loaded once when the viewer first hits your site and all subsequent loads come right from the browser cache. This is ideal. This caching efficiency easily overcomes having some unused or untriggered code in the master file that is not used in some pages.
Lots of small downloads (even from the cache) is less efficient than one larger download. More separate requests generally just isn't as efficient for either the browser or the server. So, combining JS files into larger concatenated files is generally a good thing.
There are limits to all of this. If you had completely separate code for 100 separate pages all concatenated together and each piece of code would search the DOM for multiple page elements (and not find them 99% of the time), then that's probably not an efficient way to do things either. But, usually you can make your shared code smarter than that by breaking things into categories based on a high level class name. So, for example, based on the presence of a class name on the <body> tag, you would then run only part of the initialization code, skipping the rest because its classification is not present. So, when combining code, much of which won't be relevant on any given page, it's wise to be smart in how you decide what initialization code in the shared file to actually run.

You need to measure for your specific case - as every site/page have its own balance between loading less files/loading extra unnecessary scripts (same apply to CSS too).
Generally single file is faster in HTTP v1 as there are restrictions on total number of parallel downloads, HTTP v2 should be removing the difference.

Related

Single JS script or multiple scripts? [duplicate]

I'm used to working with Java in which (as we know) each object is defined in its own file (generally speaking). I like this. I think it makes code easier to work with and manage.
I'm beginning to work with javascript and I'm finding myself wanting to use separate files for different scripts I'm using on a single page. I'm currently limiting myself to only a couple .js files because I'm afraid that if I use more than this I will be inconvenienced in the future by something I'm currently failing to foresee. Perhaps circular references?
In short, is it bad practice to break my scripts up 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.
Update from 2020: this answer is very old by internet standards and is far from the full picture today, but still sees occasional votes so I feel the need to provide some hints on what has changed since it was posted. Good support for async script loading, HTTP/2's server push capabilities, and general browser optimisations to the loading process over the years, have all had an impact on how breaking up Javascript into multiple files affects loading performance.
For those just starting out with Javascript, my advice remains the same (use a bundler / minifier and trust it to do the right thing by default), but for anybody finding this question who has more experience, I'd invite them to investigate the new capabilities brought with async loading and server push.
Original answer from 2013-ish:
Because of download times, you should always try to make your scripts a single, big, file. HOWEVER, if you use a minifier (which you should), they can combine multiple source files into one for you. So you can keep working on multiple files then minify them into a single file for distribution.
The main exception to this is public libraries such as jQuery, which you should always load from public CDNs (more likely the user has already loaded them, so doesn't need to load them again). If you do use a public CDN, always have a fallback for loading from your own server if that fails.
As noted in the comments, the true story is a little more complex;
Scripts can be loaded synchronously (<script src="blah"></script>) or asynchronously (s=document.createElement('script');s.async=true;...). Synchronous scripts block loading other resources until they have loaded. So for example:
<script src="a.js"></script>
<script src="b.js"></script>
will request a.js, wait for it to load, then load b.js. In this case, it's clearly better to combine a.js with b.js and have them load in one fell swoop.
Similarly, if a.js has code to load b.js, you will have the same situation no matter whether they're asynchronous or not.
But if you load them both at once and asynchronously, and depending on the state of the client's connection to the server, and a whole bunch of considerations which can only be truly determined by profiling, it can be faster.
(function(d){
var s=d.getElementsByTagName('script')[0],f=d.createElement('script');
f.type='text/javascript';
f.async=true;
f.src='a.js';
s.parentNode.insertBefore(f,s);
f=d.createElement('script');
f.type='text/javascript';
f.async=true;
f.src='b.js';
s.parentNode.insertBefore(f,s);
})(document)
It's much more complicated, but will load both a.js and b.js without blocking each other or anything else. Eventually the async attribute will be supported properly, and you'll be able to do this as easily as loading synchronously. Eventually.
There are two concerns here: a) ease of development b) client-side performance while downloading JS assets
As far as development is concerned, modularity is never a bad thing; there are also Javascript autoloading frameworks (like requireJS and AMD) you can use to help you manage your modules and their dependencies.
However, to address the second point, it is better to combine all your Javascript into a single file and minify it so that the client doesn't spend too much time downloading all your resources. There are tools (requireJS) that let you do this as well (i.e., combine all your dependencies into a single file).
It's depending on the protocol you are using now. If you are using http2, I suggest you to split the js file. If you use http, I advise you to use minified js file.
Here is the sample of website using http and http2
Thanks, hope it helps.
It does not really matter. If you use the same JavaScript in multiple files, it can surely be good to have a file with the JavaScript to fetch from. So you just need to update the script from one place.

What are the benefits to concatenating JS files? [duplicate]

For example, if you have
<body>
<script src="someLibrary.js"></script>
<script src="someLibrary2.js"></script>
<script src="someLibrary3.js"></script>
<script src="someLibrary4.js"></script>
<script src="myApp"></script>
</body>
What is the benefit aside from prettiness in the html to having all of those be concatenated and minified by a task running (Grunt/Gulp) before sending it to client in form of
<body>
<script src="allTheJavascripts.js"></script>
</body>
Combining multiple JS files into one file has the following benefits:
Browsers can download a single file more efficiently and faster than downloading multiple smaller files. One http connection downloading the file is usually faster than many http connections downloading smaller files.
The browser has a limit on how many simultaneous connections it will make to the same domain and, if it reaches that limit, some connections have to then wait until others finish. This causes delays in download. Downloading fewer files make it less likely to hit this limit. This limits applies to all connections to a domain (download of JS files, download of CSS files, download of frames, ajax calls, etc...).
Server scalability can be increased because each page download requires fewer http connections to serve the content.
There are cases where version control and the interaction between version upgrades and browsing JS file caching can be simpler with one larger JS file. When all your JS files are concatenated, you can assign a single version number to that combined JS file (like jQuery does with its versions). Then, any change to the JS anywhere causes a bump in the version number for the master combined file. Since a given browser gets the entire combined file all or nothing, there is never an opportunity for a browser to accidentally get one version of one file fresh from the server and another version of another file from a stale browser cache. Also, maintaining one master version number is a lot simpler than versioning lots of smaller files.
Minifying a JS file makes it smaller to download and parse which increases download performance.
If you are both combining multiple files AND minifying, the minifying can be more effective. When minifying multiple small files separately, you cannot minify variable names that are shared between the different files - they must retain their original names. But, if you combine all the JS files and then minify, you can minify all symbols that are shared among the different JS files (as long as they aren't shared externally).
Obviously, there are some limits here and things don't get arbitrarily better if the whole world puts their JS into one file. Some things to think about when deciding what to package together into one file:
You don't want a large group of your pages to be parsing and executing a large block of code that they will not use. This is obviously a tradeoff because if the code is being effectively cached, then it's not so much a download issue, but rather just a runtime efficiency issue. Each use will have to decide how to draw that tradeoff line.
You may not want to package code that is revised fairly regularly with code that hardly ever changes because this degrades the efficiency of browser caching if the large combined JS is always changing.
In a team environment with multiple projects sharing code, it is very important to think about packaging things into combined and minified chunks that work for the largest number of projects sharing the code. You generally want to optimize the packaging for the broader needs, not just for a single project.
Mobile access often has smaller caches, slower CPUs and slower connections so its important to consider the needs of your most accessed mobile pages in how you package things too.
And some downsides to combining and minimizing:
Directly debugging the minimized site can be quite difficult as many symbols have lost their meaningful names. I've found it often required to have a way of serving an unminimized version of the site (or at least some files) for debugging/troubleshooting reasons.
Error messages in browsers will refer to the combined/minimized file, not to the actual source files so it is can be more difficult to track down which code is causing a given browser error that has been reported.
The combined and minimized site has to be tested to make sure no issues were caused by these extra steps.
Many browsers limit the number of concurrent HTTP requests to a particular domain. Concatenating the JavaScript files reduces the number of HTTP requests needed, allowing the files to be downloaded faster.
The same is true for CSS files.
Separately, such combined files are sometimes put through a minification process that produces syntactically equivalent files, that are smaller.
One downside is that, if any component file changes, the cache for the entire combined file must be invalidated and the combined file reloaded. This is a very small downside for most scenarios.
Very simple:
Reduced Latency (1 file mean one HTTP GET) traded for wasted bandwidth and unnecessary
consumption of memory resources. (Scripts needs to be loaded, parsed, execute even if not needed)
More difficult to debug (1 import) vs. easier to read.
If your page is definitely going to use them all, then go ahead and load them as one. But that's a gross over assumption that generally breaks down. As a general rule, monolithic code base is bad.

Should I split my javascript into multiple files?

I'm used to working with Java in which (as we know) each object is defined in its own file (generally speaking). I like this. I think it makes code easier to work with and manage.
I'm beginning to work with javascript and I'm finding myself wanting to use separate files for different scripts I'm using on a single page. I'm currently limiting myself to only a couple .js files because I'm afraid that if I use more than this I will be inconvenienced in the future by something I'm currently failing to foresee. Perhaps circular references?
In short, is it bad practice to break my scripts up 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.
Update from 2020: this answer is very old by internet standards and is far from the full picture today, but still sees occasional votes so I feel the need to provide some hints on what has changed since it was posted. Good support for async script loading, HTTP/2's server push capabilities, and general browser optimisations to the loading process over the years, have all had an impact on how breaking up Javascript into multiple files affects loading performance.
For those just starting out with Javascript, my advice remains the same (use a bundler / minifier and trust it to do the right thing by default), but for anybody finding this question who has more experience, I'd invite them to investigate the new capabilities brought with async loading and server push.
Original answer from 2013-ish:
Because of download times, you should always try to make your scripts a single, big, file. HOWEVER, if you use a minifier (which you should), they can combine multiple source files into one for you. So you can keep working on multiple files then minify them into a single file for distribution.
The main exception to this is public libraries such as jQuery, which you should always load from public CDNs (more likely the user has already loaded them, so doesn't need to load them again). If you do use a public CDN, always have a fallback for loading from your own server if that fails.
As noted in the comments, the true story is a little more complex;
Scripts can be loaded synchronously (<script src="blah"></script>) or asynchronously (s=document.createElement('script');s.async=true;...). Synchronous scripts block loading other resources until they have loaded. So for example:
<script src="a.js"></script>
<script src="b.js"></script>
will request a.js, wait for it to load, then load b.js. In this case, it's clearly better to combine a.js with b.js and have them load in one fell swoop.
Similarly, if a.js has code to load b.js, you will have the same situation no matter whether they're asynchronous or not.
But if you load them both at once and asynchronously, and depending on the state of the client's connection to the server, and a whole bunch of considerations which can only be truly determined by profiling, it can be faster.
(function(d){
var s=d.getElementsByTagName('script')[0],f=d.createElement('script');
f.type='text/javascript';
f.async=true;
f.src='a.js';
s.parentNode.insertBefore(f,s);
f=d.createElement('script');
f.type='text/javascript';
f.async=true;
f.src='b.js';
s.parentNode.insertBefore(f,s);
})(document)
It's much more complicated, but will load both a.js and b.js without blocking each other or anything else. Eventually the async attribute will be supported properly, and you'll be able to do this as easily as loading synchronously. Eventually.
There are two concerns here: a) ease of development b) client-side performance while downloading JS assets
As far as development is concerned, modularity is never a bad thing; there are also Javascript autoloading frameworks (like requireJS and AMD) you can use to help you manage your modules and their dependencies.
However, to address the second point, it is better to combine all your Javascript into a single file and minify it so that the client doesn't spend too much time downloading all your resources. There are tools (requireJS) that let you do this as well (i.e., combine all your dependencies into a single file).
It's depending on the protocol you are using now. If you are using http2, I suggest you to split the js file. If you use http, I advise you to use minified js file.
Here is the sample of website using http and http2
Thanks, hope it helps.
It does not really matter. If you use the same JavaScript in multiple files, it can surely be good to have a file with the JavaScript to fetch from. So you just need to update the script from one place.

Speed optimizing a JavaScript function

I have a number of JavaScript functions like the following on my page:
function fun1(){...}
function fun2(){...}
function fun3(){...}
function fun4(){...}
I may use fun1 in one or two pages, but the other functions only for specific pages.
My question is: should I include all the functions in one file like script.js or include specific functions for specific page? Which one is better for speed optimizing?
I guess your question is about optimizing page loading speed.
I would suggest grouping them as mush as possible in a single js file.
Otherwise, you would have to load a lot of small js files, increasing the page loading time.
Consider minifying your JS files too.
Depends on the size of the functions, your visitors' access patterns, your cache settings and other circumstances. The speed of downloading a file depends on how many TCP packets the server has to send. (Packet sizes tend to be around 1,5K.) Increasing the file size only matters if means the file needs to be broken into more packets (the client-size delay of processing a script which needs not be run is negligible), so if your scripts are short (you should of course minify them first), its best to alwaays bundle them. If you expect the average visitor to need all scripts eventually, it's again best to send them in one file. If, however, the average visitor won't need some of the larger scripts (for example one part is only needed at upload, and only 0,1% of the visitors ever uploads something), it might be better to send them separately.
The .js files are cached by your browser. So you can include as many functions as you like in a single file. If you split them into separate files that much of additional calls are made from the browser which slows down the loading page.. Also you can compress the js files if you are concerned about the size of the .js file ..# http://javascriptcompressor.com/
It depends a lot on how your server is sending out these files. If you have Firebug, open up the Net tab and inspect your JS files. If you see a Last-Modified entry in the Headers tab, it means that you are better off putting all your JS into one file. If you don't see it, it's best to split things up into page-specific files.
In my opinion, there are four main methods of speeding up your page-load times:
server headers -- this one is more complex to set up, but if you control your server settings or if you are willing to serve your JS via a dynamic page (PHP or ASP), you can send extra instructions to the browser to cache specific content for specific periods. Since your JS files are likely to change quite infrequently, it's usually pretty safe to do this for them. You basically just need to set the Expires header to some point well into the future. This means that the browser will not need to request the file at all if it has it in the cache. This makes the most sense if you have visitors who come back again and again. If you get a lot of one-hit visitors, this won't make a difference. This does mean that if you change these files, many browsers won't pick up the change; thus you should either change the file name or append something to the query string like this: <script type="text/javascript" src="/sitescript.js?v=1.1"></script>. This can be a maintenance problem if you have more than a few static HTML pages.
numbers of files -- in my opinion, this is where you get the biggest bang-for-buck savings. I'm nearly certain that most browsers still support only four active requests at a time. That means that if your web page has five images, the last image won't get requested until one of the previous images completes loading. And if your site has 50 images and 3 CSS files and 10 JS files, it's going to take a while to clear all those requests. Remember, even if you are sending Last-Modified headers, the browser still needs to check if the content has changed, so it needs one of those request slots. If you can combine all your images into a single images (using CSS sprites) and all your JS into a single file, your pages will load significantly faster.
file size -- as the web speeds up, this gets less and less important. If your server does not support content compression, it's a pretty good idea to minify your JS, though the time savings are overrated in my opinion. This does make maintenance somewhat more time-consuming and live debugging nearly impossible, but it definitely brings file size down quite a bit. If you have a LOT of JavaScript (maybe ~150KB+?) or if you know your visitors are coming from slower networks (for example, people on a corporate network), I would recommend doing it. If your server DOES support compression, the savings are actually negligible.
script placement -- when the browser hits a <script src="..."> tag, it halts all rendering until the script has loaded and executed, which means an inevitable delay. If you put your scripts in the middle of your page, you'll note that half the page loads and then pauses. To speek up rendering, place as many of your <script> references as you can at the dead bottom of the page. Scripts that you need at the top of the page can go there, but the more <script> clutter you have up there, the slower the page will render. Any code that gets executed by onLoad or DOMReady can safely go at the bottom of the page.
Yahoo has a really quite amazing list of optimization tips at their Best Practices page.

Should Javascript be separated into files by page or consolidated into one file?

Should I be separating my js for each page assuming there is no overlap and putting references on each page instead of having one master file? what is typical practice? thanks
Everything that is common to every page of your site should be on a single file, since it will be loaded only once by the browser.
Code specific for a single (or maybe 2) page(s) should go on separate files, loaded only by the pages that need them.
That's the way I do it: you use the browser's cache to reduce your bandwidth and to accelerate the loading and rendering of the page.
For infrequently accessed pages, load the javascript inline (at bottom of all the markup) for quickest load time (one less TCP connection required as is the case for separate .js script file).
For frequently hit pages do the opposite: reference a .js script file - in this case the caching by the browser provides a greater advantage across the aggregate of page loads.
In larger projects, develop your javascript in separate .js files (you can use the module pattern for instance), then for production compile them into a single file (or a number of files per architecture of your application) with a build script.
It all depends on what kind of app you have. If your app is frequently accessed but for short periods of time then initial loading time is important and you should try to combine files.
If, however, you expect users to spend hours at a time in your app and initial load time is not critical then I would advise partitioning your .js files as much as you need to to make it readable - since they will all be cached anyway after the initial load.
Don't believe the hype. Unless you're a google search engine you should be careful not to sacrifice readability for the sake of a few seconds (or less) at initial start up. Put it another way, rules of thumb are just that, don't neurotically follow them - think first :-)

Categories

Resources