Single JS script or multiple scripts? [duplicate] - javascript

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.

Related

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.

Minification for Css/Js - right way?

In my project each page has a bunch of dependent Javascript and Css. Whilst developing I just dumped this code right into the page but now I'm looking to clean it up...
it appears that the general approach out there is to package all the Javascript/CSS for an application into two big files that get minimised.
This approach has the benefit that it reduces bandwidth since all the front-end code gets pulled in just once from the server... however, I'm concerned I will be increasing the memory footprint of the application by defining a whole ton of functions for each page that I don't actually need - which is why I had them on a per-page basis to begin with.
is that something anyone else cares about or is there some way to manage this issue?
yes, I have thought of doing conditional function creation since I need to run code conditionally for each page anyway - though that starts to get a bit hackish in my view.
also, is there much cost to defining a whole ton of Css that is never used?
Serving the javascript/CSS in one big hit for the application, allows the browser to cache all it needs for all your pages. If the standard use case for your site is that users will stay and navigate around for a while then this is a good option to use.
If, however, you wish your landing page to load quickly, since there is a chance that the user will navigate away, consider only serving the CSS/javascript required for this page.
In terms of a performance overhead of a large CSS file - there will be none that is noticeable. All modern browsers are highly optimised for applying styles.
As for your javascript - try not to use conditional function creation, conditional namespace creation is acceptable and required, but your functions should be declared only in one place.
The biggest thing you can do for bandwidth is make sure your server is compressing output. Any static document type should be compressed (html, js, css, etc.).
For instance the jQuery Core goes from approx. 90KB to 30KB only because of the compressed output the server is sending to browsers.
If you take into account the compression, then you have to create some mammoth custom JS includes to really need to split-up your JS files.
I really like minifying and obfuscating my code because I can put my documentation right into the un-minified version and then the minification process removes all the comments for the production environment.
One approach would be to have all the shared javascript minified and compressed into one file and served out on each page. Then the page-specific javascript can be compressed/minified to its own files (although I would consider putting any very common page's javascript into the main javascript file).
I've always been in the habit of compressing/minifying all of the CSS into one file, rather than separate files for each page. This is because some of the page-specific files can be very small, and ideally we share as much css across the site as possible.
Like Jasper mentioned the most important thing would be to make sure that your sever is GZIPing the static resources (such as javascript and css).
If you have a lot of javascript code you can take a look on asynchronous loading of js files.
Some large project like ExtJs or Qooxdoo have build in loaders to load only required code, but here is a lot of libs which simplify this, and you can use in your project (e.g. head.js, LAB.js).
Thanks to them you can build application which loads only necessary files, not whole javascript code which in case of big apps can be a heavy stuff for browser.

Put CSS and JavaScript in files or main HTML?

Although it is always recommended to put JavaScript and CSS code into appropriate files (as .js and .css), most of major websites (like Amazon, facebook, etc.) put a significant part of their JavaScript and CSS code directly within the main HTML page.
Where is the best choice?
Place your .js in multiple files, then package, minify and gzip that into one file.
Keep your HTML into multiple seperate files.
Place your .css in multiple files, then package, minify and gzip that into one file.
Then you simply send one css file and one js file to the client to be cached.
You do not inline them with your HTML.
If you inline them then any change to the css or html or js forces to user to download all three again.
The main reason major websites have js & cs in their files, is because major websites code rot. Major companies don't uphold standards and best practices, they just hack it until it works then say "why waste money on our website, it works doesn't it?".
Don't look at examples of live websites, because 99% of all examples on the internet show bad practices.
Also for the love of god, Separation of concerns please. You should never ever use inline javascript or inline css in html pages.
http://developer.yahoo.com/performance/rules.html#external
Yahoo (even though they have many inline styles and scripts), recommends making them external. I believe google page speed used to (or still does?) do the same as well.
It's really a logical thing to have them separate. There are so many benefits to keeping CSS and JS separate to the HTML. Things like logical code management, caching of those pages, lower page size (would you rather a ~200ms request for a 400kb cached resource, or a 4000ms delay from having to download that data on every page?), SEO options (less crap for google to look through when scripts/styles are external), easier to minify external scripts (online tools etc), can load them synchronously from different servers....
That should be your primary objective in any website. All styles that make up your whole website should be in the one file (or files for each page, then merged and minified when updated), the same for javascript.
In the real world (not doing a project for yourself, doing one for a client or stakeholder that wants results), the only time where it doesn't make sense to load in another javascript resource or another stylesheet (and thus use inline styles/javascript) is if there's some kind of dynamic information that is on a kind of per-user, per-session or per-time-period that can't be accomplished as simply any other way. Example: when my website has a promotion, we dump a script tag with a small JSON object of information. Because we don't minify and merge multiple files, it makes more sense to just include it in the page. Sure there are other ways to do this, but it costs $20 to do that, whereas it could cost > $100 to do it another way.
Perhaps Amazon/Facebook/Google etc use so much inline code is so their servers aren't taxed so much. I'm not too sure on the benchmarking between requesting a 1MB file in one hit or requesting 10 100KB files (presuming 1MB/10 = 100KB for examples' sake), but what would be faster? Potentially the 1MB file, BUT smaller requests can be loaded synchronously, meaning each one of those 10 requests could come from a separate server/domain potentially, thus reducing overall load time.
Further, google homepages for example seem to dump a JSON array of information for the widgets, presumably because it compiles all that information from various sources, minifies it, caches it, then puts in on the page, then the javascript functions build the layout (client side processing power rather than server-side).
An interesting investigation might be whether they include various .css files regardless of the style blocks you're also seeing. Perhaps it's overhead or perhaps it's convenience.
I've found that while working with different styles of interface developer (and content deployers) that convenience/authority often wins in the face of deadlines and "getting the job done". In a project of a large scale there could be factors involved like "No, you ain't touching our stylesheets", or perhaps if there isn't a stylesheet using an http request already then convenience has won a battle against good practice.
If your css and javascript code is for a global usage, then it is best to put them into appropriate files.
Otherwise, if the code is used just by a certain page, like the home page, put them directly into html is acceptable, and is good for maintenance.
Our team keeps it all seperate. All resources like this goes into a folder called _Content.
CSS goes into _Content/css/xxx.js
JS goes into _Content/js/lib/xxx.js (For all the library packages)
Custom page events and functions get called from the page, but are put into a main JS file in _Content/js/Main.js
Images will go into the same place under _Content/images/xxx.x
This is just how we lay it out as it keeps the HTML markup as it should be, for markup.
I think putting css and js into the main html makes the page loads fast.

Is using inline JavaScript preferred to an external include if the script is really short?

I use External JavaScripts in a website as I always try to keep JavaScript at bottom and external.
But Google page speed is giving this suggestion
The following external resources have small response bodies. Inlining
the response in HTML can reduce blocking of page rendering.
http://websiteurl/ should inline the following small resources:
http://websiteurl/script.js
This external js file has only this content
$(document).ready(function() {
$("#various2").fancybox({
'width': 485,
'height': 691,
});
});
But in Yslow I get this suggestion
Grade n/a on Make JavaScript and CSS external
Only consider this if your property is a common user home page.
There are a total of 3 inline scripts
JavaScript and CSS that are inlined in HTML documents get downloaded
each time the HTML document is requested. This reduces the number of
HTTP requests but increases the HTML document size. On the other hand,
if the JavaScript and CSS are in external files cached by the browser,
the HTML document size is reduced without increasing the number of
HTTP requests.
Which is right Google or Yahoo?
This is a bit of a problematic example, on quite a few fronts.
You can organise your scripts in such a way that you do not need to inline that JS. For example you could have a common.js file that runs that snippet, other similar snippets and simplifies your code.
Additionally, this seems to have awoken "never inline any JavaScript EVER" architecture police. Turns out that sometimes it is a best practice to inline JavaScript, for example look at the common snippet from Google analytics.
Why are Google suggesting you should inline this tiny script?
Because 20% of the page visits you get have an unprimed cache
If you have a cache miss, it is likely a new connection to your site will need to be opened (1 round trip) and then the data delivered in the 2nd round trip. (if you are lucky you get to use a keepalive connection and it is cut to 1 round trip.
For a general "global" English web application you are looking at a typical 110ms round trip time for a service hosted in the US. If you are using a CDN the number would probably be halved.
Even if the resource is local, the web browser may still need to access the disk to grab that tiny file.
Non async or defer JavaScript script tags are blocking, if this script is somewhere in the middle of your page, it will be stuck there until the script downloads.
From a performance perspective if the only 2 options are:
Place a 50 char JavaScript bit inline
Place the 50 chars in a separate file and serve it.
Considering that you are a good web citizen and compress all your content, the amount of additional payload this adds is negligible compared to the 20 percent risk of giving people a considerable delay. I would always choose #1.
In an imperfect world it is very rare to have such a clear and easy set of options. There is an option 3 that involved async loading jQuery and grabbing this functionality from a common area.
Making scripts inline can have some detrimental effects -
a) Code organization - Your code gets scattered in between your markup, thus affecting readability
b) Code Minification and obfuscation becomes difficult
Its best to keep your js in seperate files, and then at build time integrate all of them into a single file, and minify and obfuscate this.
This is not quite true. You can configure the web server (well atleast apache) to make the scrips/ccs inlined when they are served.
Here is a useful link
http://www.websiteoptimization.com/speed/tweak/mod_pagespeed/
There are two factors to consider here. One is download time, the other is maintainability. Both of these are impacted by how many times a piece of Javascript is needed.
With respect to download time, you obviously have two choices: include the JS in the body of the page, or as an external file. Including the JS in the body does save an extra HTTP request, although it also bloats the HTML a bit and can be a pain to maintain if you have several scripts you're putting inline on several different pages.
Another important consideration is whether or not the JS is needed immediately on the page. If a small piece of JS is needed as soon as the page loads, then putting it inline may be a good idea. If it's being used for something asynchronous in the future, then putting it an external file may still be a good choice.
I usually write javascript inline, especially if the script is this small. I would say just paste it in your code. It won't increase the http document size by a lot.
While inlining the script will save a request, as Yslow suggests it increases the HTML document size, and mixes content/markup with code/logic, which you generally want to avoid from as much as possible.
The reason Yslow gives this caveat:
Only consider this if your property is a common user home page.
Is that if the page is loaded frequently, it's worth it to have the javascript external, since the files will be cached in the browser. So, if you combine your JS into one file, on the first request you incur one extra request, and on subsequent requests the file is loaded from the cache.
Aaron Peters talk from last year's Velocity EU gives a good insight into the options, and course you should choose - http://www.slideshare.net/startrender/fast-loading-javascript
For really small snippet of js it's really not worth putting them in an external file as the network overhead of retrieving them will dwarf the benefits.
Depending on the latency it may be ever worth including large scripts e.g. Bind mobile has loads of js in the first page loaded which it then cached in localstorage for later pages.
Addy Osmani recently put together a experimental library to help people play with caching scripts in localstorage - http://addyosmani.github.com/basket.js/

Only running javascript required for current page, best methods?

So I know it's best to have one javascript file for an entire site to limit http requests. So obviously only some javascript is required for some pages. What is the best way of only running the javascript required for the current page?
EG.
if(page=='home'){
//run javascript require for the home page
}
Maybe this isn't an issue and if targeting elements are not found on the page javascript will just fail gracefully? I would just like to know the best practice for this javascript structure.
Encapsulate your logic in functions. Then just call the function(s) you need in each page, either via "onload" or an embedded function call in the page:
<script type="text/javascript">
yourFunctionForThisPage();
</script>
Edit: Just to clarify: my answer is assuming the (implied) constraint of a single .js file. As others have pointed out, although you save on HTTP requests, this is not necessarily a good idea: the browser still has to parse all the code in the file for each page, whether used or not. To be honest it's pretty unusual to have a global site-wide js resource with everything in it. It's probably a much better idea to logically split out your js into various files, i.e libraries. These libraries could be page-based - i.e specific code for a particular page, or algorithm/task-based that you can include in whatever pages need them.
Is this feasible?
While it is best to have just a single Javascript file per page to lower the number of requests yet it may not be feasible. Especially the way that you'd like to do it.
If you're asking how to join various scripts of various pages into a single script and then running just those parts that are related to a particular page then this is something you shouldn't do. What good is it for you to have one huge file with lots of scripts (also think of maintainability) compared to a few short integrated scripts? If you keep the number of scripts low (ie. below 10) you shouldn't be to worried.
The big downside is also that browser will load the complete script file which means it will take it more time to parse them as well as consume a lot more resources to use it. I'd strongly suggest against this technique of yours even though it may look interesting...
Other possibilities
The thing is that the number of Javascript files per page is low. Depending on the server side technology you're using there are tools that can combine multiple script files into one so every page will just request a single script file which will combine all those scripts that this particular page will use. There is a bit overhead on the server to accomplish this task, but there will be just one script request.
What do you gain?
every page only has scripts that it needs
individual script files are smaller hence easier to maintain
script size per request is small
browser parsing and resource consumption is kept low
Know what you will need on the page and use a script loader like labjs.
Also, remember that your specific case might be different from what others have found, so you might want to do some tests, to verify if, for example, having 5 little files, is better (or worse) than 1 big file.
The only way to be sure is to test different options yourself and come up with a fitting solution.

Categories

Resources