Load a whole directory of css/javascript - javascript

My question is two-fold would it be possible to load a whole directory of css or javascript? And would there be any advantage to doing so?
Example - For an ecommerce store you might have a bunch of additional css and javascript that is required for functionality/styling. Putting all the javascript files required in js/checkout directory and then importing the whole directory would seem to be more streamlined than calling each one individually.
Is it possible to do this?
Or is there some reason it would be a bad idea?

Rather than loading them individually, add a build step to your deployment so that you can minify all of the CSS and JavaScript into two files. Then serve those two files so that only send two things instead of potentially many many more.
Additionally, although creating a build system from scratch can be "fun", you may want to look into some of the build tools that already have a big following. I've used Dojo Toolkit before and it works well. You would get Asynchonous Module Definitions (AMD) from using it which could also reduce the number of requests you need to make. Another particular JS build system that I've heard mentioned quite often (although I haven't used it yet) is Grunt.
Note, there is a trade off choice. Using AMD can help you reduce the overall number of requests that you make to where you only load the scripts that you use. Compare this to downloading one gigantic JS file that holds all possible scripts.
One Mega Script
If you have 100 5kb script files, one mega minified script could (if there were no size gains from semicolons, name mangling, and linebreak removal) be 500kb. It would take one request to receive that script and let's pretend that a request takes 1kb on average. That means that, in total, the mega script would cost you 101kb.
AMD
Now consider the cost if you use AMD. Let's say on a particular page you only use 7 of those 5kb scripts and that the request still only takes 1kb. Let's also pretend that the overhead of the AMD library is 10kb. That page would cost 52kb ((7 * (1kb + 5kb)) + 10kb)
As you can see, using the AMD method rather than the build will cause for more requests, but give you a net gain in terms of cost. This ALSO doesn't account for caching things that have already been loaded before.
Also, if a user navigates your entire site, visiting every single page, causing every single script to be downloaded, then it will have cost you 610kb (100 * (5kb + 1kb)) + 10kb. However, if you go with the minified script, it would only cost you 501kb.
Oh, and don't think that AMD vs One Mega Script has an impact on minification. In both cases, minification is helpful in reducing request size.

Related

Angular 2 page size

I am just getting started with Angular 2. It actually makes me think about the size of the page just for the Hello World.
Please look at the scripts which were actually needed and it already is 1.75 MB.
Offcourse with minification it would reduce 30-35% approximately.
Yet it would still be above 1 MB just for this junk Hello World type application. Adding bootstrap CSS / Jquery / Jquery UI at the minimal would take it even further plus add images depending upon the web application type.
Question is 1.75 MB of script without writing a single line of code pertaining to the application.
Is this the new web standard to make the page size on an average above 4-5 MB?
There are several strategies that will reduce the total size of your site.
Enable gzip compression for your assets. Most text files (like JS files) compress very well due to lots of strings that get repeated.
Use the minimised versions of libraries, as you identified.
Use CDN references to 3rd party libraries if possible. That way, the user may already have the file in their cache and don't need to refetch it. Some CDNs also support HTTP/2, meaning that more files can be requested in parallel.
Take advantage of the Ahead-Of-Time compilation (AOT, a.k.a. offline compilation) in Angular 2 RC 5, and swap to using the version of Angular 2 without the compiler. That saves about half of the size of the Angular 2 library file.
Use HTTP/2 yourself for your assets, and refer to each JS file individually, rather than bundling it. That way, if they haven't changed, the user won't need to download them again when they reload. And the first time, all the files can be fetched in parallel.
Use conditional comments or server side processing to remove the shims and other JS files that are only relevant to certain browsers like IE. That way, other browsers don't download those useless scripts.
Use something like Rollup or another tool that can do "tree shaking" to remove unused code.
There are probably other ways to save even more, but this is a good starting point.
Angular2 is going to get smaller in smaller now. See ngconf about this. Its mainly result of tree-shaking minification (loading only code, that really used).
Angular 2 seed project, wich in prod build loads with ~300kb is already available for use.

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.

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

Which is better for JavaScript load-time: Compress all in one big file or load all asynchronously?

A simple question that I'm not sure if it has a short answer!
Description
I have a files of JavaScript that to be loaded in a website here are some notes about them:
They are all comes from the same domain (no cross domain loading needed)
They are identical around the website.
There are several files, like jQuery, and 5 other plugins plus my own application script that is based on them.
Their size all compressed = 224KB, ( I combine all the files in one file then I compress them at once using YUI Compressor 2
Problem
I've heard that 224KB is not ideal to be in one file! and it should be split into several files with maximum of 44KB each .. I can't recall when I've heard this and I'm not sure if it's effective to split it into more files, but It's true that 224KB takes long time to load for the first time, consider that the website is loaded with images and css of course.
I've minimized the need for the early loading of JavaScript file and put it on the bottom, so far this is a good progress but I need to load it assynchounosly with the HTML to gain time Source and the decission to make is:
Yes or No?
Keep it in one compressed big file? or to split them into many compressed file and loaded a asynchronously (I'm aware of handling the dependency related problems)?
It depends on what the site is and how important first load time is for it.
Regardless of that though, I'd probably load JQuery and stuff like that from a public CDN. One big benefit is that it might already be cached even if they have never been to your site.
http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/
The Cappuccino team is a big proponent of one file -- they make a javascript framework. Apps made with their tool are expected to have some load time.
http://cappuccino.org/discuss/2009/11/11/just-one-file-with-cappuccino-0-8/
Another benefit of loading JQuery and related from a public CDN would the increased requests by destination. I believe the client is restricted to 2 requests per domain, so by loading jquery from google, and a plugin from jquery, and your custom app code from your own domain, the browser can execute these concurrently rather than waiting for the first two and then issuing a third request.
I guess this adds another performance improvement over one large file as well. Even if you just split that 1 file into 2, it could be retrieved with 2 concurrent requests from the browser potentially improving load time.
Here's what we did to make our web app fast.
The main JS and CSS files are compressed and put inline with the HTML markup.
The white spaces of the HTML are removed and the images are converted to data:image/png by a shell script.
The size is ~400kb but cached and gzipped.
The mobile version of the web app is the same but at ~250kb.
It means the whole app is ready to run, like an executable, in a single http call.
Then a second http call get the data(JSON), and we use PURE to render it in HTML using the existing markups in the page as templates.
The app is divided in modules, only the common modules are preloaded this way.The others are coming when requested by the user.
There is no exact answer to this question. It pretty much depends on how and when you are making use of those files.
Typically, you only want to download JS files on pageload which are universally required by the web app. Module specific or page specific JS files shouldn't be compressed in the main JS download and would ideally be loaded on demand.
Also, this question is valid only if you are concerned about user experience for first time users. The JS files would be cached anyways for every other visit.

Categories

Resources