JavaScript build options/tools - javascript

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

Related

Performance on phonegap

Resently I have created an PhoneGap app.
Now I want to make more Efficient as it is very slow.
So I am searching on google & SO that minify version is make more faster then regualar .js file
also according tho this.
css best practices - combining all css into a single stylesheet?
keeping everything on file is good thing from fatching file from server but as in Phonegap app everything is at client side.
now my Questions are
1) does minify improves notable performance?
2) is it good Practice to make diffenet .js file or put everything on same is good one?
For your two questions my answer is quite similar.
2) Yes is always a good practice to write javascript in a different file as when you include that the file in you page almost every browser provides you the caching.
For the first time broswer looks into the cache and download the .js file from the server and store in its cache.
When again the same file is included it wil not download the js file but will refer to the cache.
This surely improves the performance.
1) As I explained above for the first time evrey js file gets download to client side. Now if you minify the js the download size will be very less hence will improve you performance. But it doesnt mean that you javascript code will start performing faster when you minify the js file.
Both the cases will improve the performance in some manner.
yeah you are right that why one should create a minify verstion of script if everything is going to run on client side , but in my experience there are two main benifits :
-One is while creating minify version , the compiler guides you about best practices and creates warning where required ( sencha cmd does).
-Other point is your app does reduce in size.
-You can have clean production version of your app.
Thanks
Here's some alternative approach to it.
Basically minifying and deferred loading of JavaScript files is a good practice. However, you can also consider trying native UI widgets on your apps to render the page much faster.
I am using Monaca for a while and found its native component very efficient and high performance. It's open-source as well. Take a look at the API reference.
The alternative solution is to use Steroids. It is closed-source, but it provides similar functions and components.

When to use Requirejs and when to use bundled javascript?

This may be a dumb question for web guys. But I am a little confused over this. Now, I have an application where I am using a couple of Javascript files to perform different tasks. Now, I am using Javascript bundler to combine and minify all the files. So, at runtime there will be only one app.min.js file. Now, Requirejs is used to load modules or files at runtime. So, the question is if I already have all things in one file, then do I need requirejs? Or what is a use case scenario where I can use requirejs and/or bundler?
Please let me know if any further details are needed.
Generally you only use RequireJS in its loading form during development. Once the site is done and ready for deployment, you minify the code. The advantage here is RequireJS knows exactly what your dependencies are, and thus can easily minify the code in the correct order. Here is what it says on the RequireJS website:
Once you are finished doing development and want to deploy your code for your end users, you can use the optimizer to combine the JavaScript files together and minify it. In the example above, it can combine main.js and helper/util.js into one file and minify the result.
This is a hotly contested issue among many proficient javascript developers. Many other languages have a "compilation" phase where the entire program is bundled up for deployment (JBoss's .WAR files come to mind). Programmers that come from more traditional backgrounds often favor this approach.
Javascript has seen such growth in recent years that it is difficult to chart exact best practices, but those that appreciate the more functional nature of Javascript often prefer the module loading approach (like require.js uses).
I wrote Frame.js which works much like require.js, so my bias is towards the module loader approach.
To answer your question directly, yes, it is one or the other.
Most that argue for packing your scripts into a single file believe it enables more compression and is thus more efficient. I believe the efficiency advantages of packaging are negligible in most cases because: (1) module load times are distributed over the entire session, (2) individual modules can be compressed to nearly the same percentage, (3) individual modules can be cached by the server and routers separately, and (4) loading scripts only when they are needed ultimately allows you load less code for some users and more code overall.
In the long run, if you can see an advantage to dynamic script loading use it. If not, bundle your scripts into a single file.
It depends on your application. If you're making a server-side app with only modest javascript (less than 100kb minified) then go for total bundling, you're probably going to be fine.
But if you're making a javascript app and have a ton of code in it, then your needs are going to be different.
For example, in my app I bundle all the core files. There's jQuery, underscore, backbone, my main app files, my user login system, my layout system, my notifications and chat system, all are part of my big initial file.
But I have many other modules as well that isn't part of the initial bundle, that are loaded after those.
The forums, the wiki, the wysiwyg, color picker, drag/drop, calendar, and some animation files are part of the second category. You need to make reasonable decisions about what's commonly used and needed immediately vs what can be delayed.
If I include everything immediately I can get above a meg of javascript, which would be insane and make the initial boot unacceptably slow.
The second category starts downloading after initSuccess event fires from the initial file.
But the second category is more intelligent than the first in that it loads what's more important first. For example if you're looking at the wiki it'll load the wiki before it loads the color picker.

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.

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...

HTML + JavaScript + CSS compact tool

I need a tool which can minify, optimize and munge many files of those possible types
HTML (minify only)
JavaScript (minify, optimize and munge)
CSS (minify)
The final result should be one HTML file only with all JavaScript and CSS embedded or in the worst scenario 3 files respectively for HTML, JS, and CSS.
I am aware of tools like YUI Compressor etc. What I currently have not found is the type of compressor which will work on all those file types and merge them in one huge file only.
If you're not using gzip yet, start using it already and we can close this thing out ;)
My suggestion would be to put all of the JavaScrpt inside a <script> in the header, and put all of the CSS in a <style> tag as well. Then optimize to the best of your ability and then minimize it on your own. No software will ever be able to handle every case. If you are trying to minimize the file size then just remove the newlines and non-necessary spaces.
I also found this, which should work on your file with all 3 in it.
Also be aware that if you start removing optional tags you could run into some problems. Some browsers don't cooperate as well as they are supposed to.
Gad, consider the drawbacks to minifying CSS. If you don't have a system where you edit normal/minify/ then deploy it can make later editing of CSS rather dicey.
I went through this whole argument on a big UI refresh project for an international bank. One site in particular was doing 1million+ visitors/day and bandwidth numbers were insane despite all our efforts to keep it minimal (every little bit adds up on a site that heavily trafficked) Upon business analysis by a large team of very talented minds, it was determined that we would take several steps, but NOT css minifying due to the added time it would take engineers to undo the minifying before fixing, minifying and redeploying for simple CSS tweaks. The numbers showed that even with a 5gb/day bandwidth improvement, it was still cheaper to not pay a UI engineer for the extra time.
We don't know your site's specifics, but there aren't terribly many that have to worry about the traffic my example uses. Run your site in Firebug's new speed analyzer and see what the real benefit could be from minifying.....now multiply that by your traffic. Usually, that number isn't too scary. Spend your time doing image sprites, combining css and js into respective files (better than mashing into individual php files due to caching benefits) to limit http requests, and ensuring that caching is properly setup. Run gzip compression. If after those steps you're not good, then take the site to a new level.
Keep it simple....it makes a huge difference in the update and maintenance portions of the site's lifecycle. With the time and headache saved, you can help us out with our questions :)
As far as I know there isn't such a tool. If you use PHP on the server side, however, you can try PHP Speedy (not actively developed, but works) or Minify for automated minification, caching and gzipping (HTML, CSS, JS).
edit: kangax's HTML minifier (as Badger suggested) only does HTML minification.
you can use jsCompressor to compress and minify multiple JavaScript files and CSS Compressor to compress/minify multiple Css files into one file.
and to optimize your HTML files you may send post request of your code to Google Clouser server which sends response with optimized Html code.
http://prettydiff.com/?m=minify will do exactly what you need, except that it only minify JavaScript and not obfuscate it.
I suggest you look at the build script that's included in the html5 Boilerplate: http://html5boilerplate.com/. With some minimal tweaking it'll do what you're looking to do.

Categories

Resources