Best Way to Organize JavaScript Files - javascript

So I have web app with multiple JS files (jQuery, jQuery, my own JS code and more). Say I have a page named index.html. What would be the best practice to include / preload my js files? I was thinking about creating a separate JS file that will do the preloading (include all the other scripts and call jQuery.noConflict()). What do you guys suggest? Is this possible? How would you implement it?
Thanks!

In general, combine your script files into one file (and minify or compress them, or even compile them, but note that this last item is not zero-impact, there are pain points). See notes here and here. Basically, one of the first guidelines you'll see for a good fast page load is "minimize HTTP requests." So you don't want six separate script tags where you could have one.
For popular scripts, though, you may benefit from using them from Google's CDN. Google is kind enough to host most popular JavaScript libraries on their CDN for free. The advantage here being not only that the CDN will be fairly fast, but that the target user's browser may well have a cached version of the script you want to use even though they've never been to your site before.

Check out RequireJS, a smart and robust script loader for JavaScript. It's designed to work well with jQuery and comes with an optimization tool to combine all of your scripts into one.

The best way is to minimize all the js files and combine them into one script. This will cause less work for the browser, as it doesn't have to make multiple requests to the server.

If you are going to load everything up at the same time, you could put it all into a single compressed file

Related

Put javascript and css inline in a single minified html file to improve performance?

A typical website consists of one index.html file and a bunch of javascript and css files. To improve the performance of the website, one can:
Minify the javascript and css files, to reduce the file sizes.
Concatenate the javascript files into one file and similar for the css files, to reduce the number of requests to the server. For commonly used (and shared) libraries like jquery it makes sense to leave them external, allowing the browser to cache the library and reuse it in different web applications.
I'm wondering if it makes sense to put the concatenated javascript and css file inline in on single html file, which will reduce the number of requests even further. Will this improve the performance of your site? Or will it work reversed, making it impossible for the browser to cache anything?
Concatinating your CSS and JS files into one file will reduce the number of requests and make it load faster. But as commented, it won't make much sense unless you have a one-page site and the load time of that page is very critical. So you're better off to separate CSS from Javascript in my opinion.
Here's a book where you can learn more about the topic:
High Performance Web Sites
this tools maybe help you.
Turns your web page to a single HTML file with everything inlined - perfect for appcache manifests on mobile devices that you want to reduce those http requests.
https://github.com/remy/inliner
It would cut down on the number of requests but it would also mean no caching of those for use on other pages. Think of defining an external file as also a way to tell the browser "and this section of the site is reusable". You'd be taking that ability away and so the CSS and JS would load. Like jackwanders said it's great if you only have one page.
This is not a good idea for the following reasons:
You will not enjoy the benefit of cache
You will load unneeded resources in all of your pages
You will have a hard time while developing your website because of large files with unrelated code branches
If you work in a team you will have to work with your teammates on the same files always, which means that you will have a lot of merge conflicts.
You can have a single CSS for all your pages and since it will be cached, the subsequent pages will refer it from cache without sending extra request.
However, putting all Javascript files is into one is contextual.
Most probably you might be using libraries like jQuery, and relevant plugins. This 'might' throw conflicting issues between plugins. So, before you try it all at once, try merging few files at once and checking if the error pops or not.

Bundling .js files vs CDN

In order to improve performance of our web pages, we are recommended to use CDNs to serve .js files on our web pages. That makes sense.
Also, we are recommended to bundle our .js files in order to reduce the number of requests which are being made to server on load.
So, we need to sit down and make decision between if we use CDN or bundle .js files.
What are the pros and cons? Which ones make more sense?
Why can't you bundle them and place them are the CDN? It should hardly be a decision of one or the other?
If you have to choose one or the other, it depends on how many .js files you are including. For a small number of files, I'd suggest that a CDN would be quicker, where-as for a greater number of files, a bundle of .js files would definitely be quicker. Where the switch-over would be, is something for you to experiment with.
My answer: both. Bundle them and place them on a CDN.
The downside of doing this? Depends. What does you build process look like? Can you easily automate the bundling and minification? Are you using Yahoo YUI or Google Closure or something else?
Also, if there is a lot of GUI dependent jQuery there might be some time consuming friction due to constantly changing elements/effects/css.
Testing is important too because due to possible minification quirks.
Bottom line: 5 javascript files safely bundled into 1 file === 4 fewer requests.
A page with just plain old Html and one external javascript reference === 2 requests to your server. However, a page with just plain old Html and one external javascript reference on a CDN === 1 request to your server.
Currently we are using the Google Closure tools. The Google Closure Inspector helps with the following:
Closure Compiler modifies your original JavaScript code and produces code that's smaller and more efficient than the original, but harder to read and debug. Closure Inspector helps by providing a source mapping feature, which identifies the line of original source code that corresponds to the compiled code.
As others have already stated, the answer is both if possible. Bundled (and minifying) gives a benefit to your users because it decreases the page weight. The CDN benefits your servers because you are offloading work. Generally speaking, you need not optimize either unless you have observed performance issues or you just have nothing better to do.
There's a few things you need to think about...
How much of the JS do you need to load early in the page load, and how much can you delay until later?
If you can delay loading JS (e.g. put it at the bottom of the page) or load it asynchronously as Google Analytics does, then you will minimise the amount of time downloading the JS spends blocking the UI thread.
After working out how the load of the JS can be split, I'd deal with the merge / minify of the various JS files - cutting down HTTP requests is key to improving performance.
Then look at moving to the CDN and ensure the CDN can serve the JS content compressed and allow you to set headers so it's "cached forever" (you'll need to version the files if you cache forever). A CDN helps reduce the latency but will also reduce size by being cookieless
Other thing you might want to consider is setting up a separate domain for static content, point it to your server(s) while you sort things out and then switch to a CDN if it looks worthwhile.
Andy

Multiple JavaScript files, combine into one

I am developing in ASP.NET MVC and using multiple JavaScript files. E.g. jQuery, jQuery UI, Google Maps, my own JavaScript files, etc.
For performance, should I combine these into one? If so, how?
The reason you want to combine many files into one is so to minimize latency of setting up and tearing down http requests, the fewer you make the better. However, many newer browsers are downloading JavaScript files in parallel (still executing sequentially). The consequence is that downloading a single 1Mb file may be slower than three 350Kb files. What I've come to do is to separate my files into three bundles:
External lib files (jquery, flot, plugins)
Internal lib files (shared by multiple pages)
Page specific files (used only by that page, maybe by two pages)
This way, I get the best of both worlds: not an excessive number of http requests at startup, but also, it's not a single file that can't benefit from parallel downloads
The same applies to CSS, each page load three CSS bundles. So in total, our pages download six bundled files plus the main html file. I find this to be a good compromise. You may find that a different grouping of files works better for you, but my advice is don't create a single bundle, unless it's a one page app. if you find yourself putting the same file into different bundles a lot, it's time to re-think the bundling strategy since you're downloading the same content multiple times.
What to use? Martijn's suggestions are on the money. YUI is the most widely used from my experience, that's what we used at my previous and current jobs.
For the question of whether you should, check out the link in Shoban’s comment.
For the question of how:
Google’s Closure Compiler
Yahoo!’s YUI Compressor
If they are all going to be included on all of your pages, then it doesn't really make a difference. But if some are only relevant to certain pages, it would technically be better to keep them separated and only include the relevant ones on relevant pages.
As far as I know, you should indeed : less files means less http get, hence better performance for the user when they first load the page.
So they will save a split second they will come on your page for the first page. But after, these files are cashed, and it makes then no difference at all...
I haven't digged into the javascript engines itselves, but a function in one file will be handled in the same way if it is in a big file or a small file. So it makes no difference in the execution.
So, save your time, don't change anything as it'll cost you too much time for too little reward, especially when you'll discover that you want the latest version of jquery (a new version came out today btw), and that you have to re-concatene everything...

Loading Javascript : HTTP Requests -v- Asynchronous Loading

I'm having difficulty in deciding which approach is better in terms of site performance.
Either to have all required jQuery plugins in one file to be included on every page on the site OR split the plugins out to individual files and use the jQuery.getScript() method to load them as and when required.
Is there any real benefit in loading the scripts asynchronously over one http request?
All my Javascript will be minified and gzipped.
Thanks!
It's not so simple and depends on the distribution of javascript across your site. Have a look at this question : Which is better for JavaScript load-time: Compress all in one big file or load all asynchronously?
From my poit of view the best solution until now is controljs
Read the complete post http://www.stevesouders.com/blog/2010/12/15/controljs-part-1/
One request will be better for performance. Period. Only downside is, every time one of the files changes, the whole thing changes (and will have to be downloaded again). Plugins won't change much, so I'd put everything (as much as possible) in 1 file.
Put jQuery core in that file as well. And your custom javascripts as well. Just make sure it's in the right order :)
Try the YSlow plugin to Firefox and try your different setups.
That said, minifying your js to one file would be an easy way with great results. You will get one file, and it's often very much smaller than the sum of the parts.

JavaScript build options/tools

These days I find myself shifting out more and more work to the client side and hence my JS files tend to get bigger and bigger. I have come to the point where most HTML pages have half a dozen or more JS imports in the header and I realised that this is hurting loading times.
I have recently discovered this script which lets you download several JS files with one HTTP request. It is written in PHP and being a Django fan I'm planning to rewrite it in Python. I'm planning to use a HTTP redirect to the pre-minified and concatenated file and was wondering what the cost of a 301 would be. Please let me know if that is a stupid idea.
On the other hand, am little worried about introducing scripting logic into the serving of static files and I was wondering if there is a viable build alternative like, say, an ant task that concatenates and minifies JS files and replaces multiple JS downloads in a HTML header with one big one, like the script does.
For PHP I certainly favour doing it dynamically just because if you introduce a build step you're losing one of the main benefits of using PHP. In fact, at the risk of self-promotion I've written Supercharging Javascript in PHP about this very issue.
Of course other technologies may vary.
Again it is PHP but it's not just a lump of code for you to use (although you can jump straight to Part 6 if you just want some fully working code) and may have value to you in terms of identifying the issues and doing things the right way and why you do them that way.
I favour having bundles of Javascript files (maybe only one for the entire application) and then each page simply activates the behaviour it needs through standard means but all the code bodies are in the larger cached and minified JS file. It works out fastest this way and is a good way to go.
If you do want it as part of a build process, which is a reasonable solution if you have a build process anyway, then I suggest you minify your code. There are lots of tools to do this. Have a look at YUI Compressor.
If you do a static combine of JS files, the other stuff mentioned above such as gzipping and associated issues is still relevant.
YUI compressor is a good choice. If you want to learn how to set up an Ant-based build process, have a look at this Tutorial: http://www.javascriptr.com/2009/07/21/setting-up-a-javascript-build-process/
As a Ruby-based alternative, I would recommend Sprockets

Categories

Resources