Bundling and Minification dynamically - asp.net

I have a question about bundling. Think about a situation like this. Take jquery DataTables for example. It has few plugins that you can use as and when you need them. In some pages, just using the base script files will do the job. but in another page, I might need to use Fixed Header plugin, in another page I might need to use Fixed Header plugin as well as Table Tools plugin.
What is the best way to approach these kind of situations in bundling. Should I create just one bundle which include all of the script files (even the ones that I might not use in some pages but in others) or create bundles specifically to each page or is there a better way of doing this. I'd like to be able to do something like
Scripts.Render("~/bundles/datatables", "FixedHeader", "TableTools")
which will include the relevant files and minify them.
Any help really appreciated.
Thanks,
Amila

Part of this, no one can answer for you. Bundling is always a trade-off: you're reducing requests at the cost of a larger file that has to be downloaded. You'll personally have to weigh the additional weight added by those scripts in the initial request versus the time it will take to request them later.
As a general guideline, this will mostly be about your audience. Do you expect a high number of mobile users? At least in the U.S., mobile data is expensive and fairly limited (because of the outrageous cost, people try to choose the lowest data tiers possible). Forcing your mobile users to download a large JS file which includes code that may never be run, is a waste of their data. While, if your target will be desktop users, a big file is no problem and is in fact preferable, as there's no concerns typically over data usage and the page load times for other pages will be improved. Even with mobile, though, sometimes users prefer faster page loads over less data usage, so even that has to be judged.
That said, if you don't choose to bundle them all together from the start, you can actually create bundles on the fly.
#{ BundleTable.Bundles.Add(new ScriptBundle("~/bundles/onthefly").Include("~/Path/To/Some/Script.js")); }
And then, as usual:
#Scripts.Render("~/bundles/onthefly")

Please take a look at the Enfold project. It might be able to accomplish what you need.
Assuming you have the following views in the web project:
~/Views/Home/About.cshtml
~/Views/Home/Contact.cshtml
~/Views/Home/Index.cshtml
You can organize your Javascript files this way:
~/Scripts/Views/default.js
~/Scripts/Views/Home/default.js
~/Scripts/Views/Home/about.js
~/Scripts/Views/Home/contact.js
~/Scripts/Views/Home/index.js
With such a setup, the following bundles will be created:
~/bundles/home/about
~/scripts/views/default.js
~/scripts/views/home/default.js
~/scripts/views/home/about.js
~/bundles/home/contact
~/scripts/views/default.js
~/scripts/views/home/default.js
~/scripts/views/home/contact.js
~/bundles/home/index
~/scripts/views/default.js
~/scripts/views/home/default.js
~/scripts/views/home/index.js

Related

Why separate vendor CSS & JS from custom CSS & JS in a workflow?

I've been trying to determine the reasoning behind what seems to have become the standard practice in Front End workflows of separating vendor JS & CSS from custom JS & CSS. I'm not sure what the benefits are over the disadvantage of an extra HTTP request, it would seem cleaner to just have a single CSS & JS file rather than having vendor.css, main.css & vendor.js, main.js.
Can anyone shed some light on this?
Vendor code typically changes less frequently than your application's code. Thus as you update your application, the vendor code can remain unchanged and cached in your user's browser.
In the scenario where vendor code is bundled with application code, the user has to download all of the vendor code every time you update the application.
The extra HTTP request from the separate vendor bundle is mitigated by the fact that the user will download less code on each application update.
I can think of two reasons.
Hosting vendor code separately from your code (e.g. Google Hosted Libraries)
Separation of concerns: the vendor code might be large and is updated independently of your custom code. Maintaining your code in a separate file avoids the need to put vendor code into your source control, makes it easier to navigate your code, makes it easy to upgrade to new vendor code since you know for certain the vendor code has not been tweaked.
Especially since you tagged the question with grunt, the end user might never see this change since you can merge vendor and user styles/scripts during the build.
However, if vendor code is large and changes infrequently, you do get a caching benefit from having a rarely changing, large vendor file accompanied by a small, fast changing custom code file. For large sites that do not use a CDN (hopefully, not yours), the impact can be noticeable.
Depending on your situation, this allows you to make your edits lower in the cascade so you can override vendor styles and behaviors without blowing away their code. This is helpful so that you always have a working version(vendor code) you can revert to. In situations like working with Wordpress, developing a child theme allows the parent theme to be updated without blowing away your customizations.
Various answers already addressed this but i'll make it very specific:
Vendor code might change more or less frequently than your code. If
vendor code changes more frequently, e.g. for bug fixes, you would
want to use the newer versions and have a better overall website.
If vendor code changes LESS frequently than your code, you may wish
to change your code w/o touching working stuff.
Vendor code is often hosted on CDNs, for example https://cdnjs.com/#q=ajax or
https://developers.google.com/speed/libraries/ These are FAST
loading. They also wont change, so the user can rely on cached
files and thus your website will load up faster.
It is generally better to make iterative changes to code. It is also easier to manage code, esp with source control when specific
things are changing. No need to swap large files when they have not
changed. Keeping things separate makes it easier to make
incremental changes, esp if the two things have different change
velocities.

Modularizing CSS files

Many people say to keep the number of external CSS and JavaScript files to minimum to reduce round trip time. For example, Google recommends maximum two CSS and JavaScript files per web site, respectively.
The problem is, I've broken up CSS code into several files depending on its nature as part of "modularization". For example, I've put CSS code that is only used in a certain part of the application in a separate file. As a result, some files have less than a hundred lines of code.
I'm a Java develper, and this is actually a recommended practice in Java, but CSS is a totally different creature and I don't know much about CSS. Here are my questions.
Does it make sense to keep as many CSS files as you see fit for readability and maintainability?
How many CSS files are manageable in a web project?
What's the average number of CSS files in web applications that you've worked on in the past?
The best solution is to write a script that combines (and minifies) multiple CSS or JS files.
You might benefit from a solution like Bundler, or Chirpy
http://www.codethinked.com/bundler-now-supports-css-and-less
http://chirpy.codeplex.com/
We use chirpy because we found a bug in Bundler that can inject query string params into you css files.
As a bonus to file consolidation, you also get .less syntax handling.
I agree with what other have said here, yes when you develop you have muliple CSS files, but for production you should merge an minify them.
However I do not agree you should merge them all into 1 single file. As the will mean people who just want to visit your home page must wait for CSS on pages x,y,z also to download.
What I usually do is have 2 or 3 CSS files.
1 small CSS file just for the home page only so it load super quick so casual visitors do not have to wait to see what my site is about
Another CSS file for every other page availble to guest users
Another CSS file for a members only sectons of the website that require a login.
You can also use scripts like HEAD.JS which will manage your CSS and javascript asynchronously
From there site http://headjs.com/
There is a common misbelief that a single combined script performs best. Wrong:
latest browsers and Head JS can load scripts in parallel. loading 3 parts in parallel instead of as a single chunk is usually faster.
if an individual file is changed the whole combination changes and you loose the benefits of caching. it's better to combine only the stable files that doesn't change often.
many popular libraries are hosted on CDN. you should take the advantage of it instead of hosting yourself
iPhone 3.x cannot cache files larger than 15kb and in iPhone 4 the limit is 25kb. And this is the size before gzipping. if you care about iPhones you should respect these limits.
As you point out, having multiple CSS files often leads to better maintainability and modularity.
The number of CSS files needed depends on the size of your project and the level of modularity in the project.
Serving up on CSS file instead of many often makes a noticeable difference in the page loading time, so the ideal solution is to have some kind of tool that combines, and maybe even compresses, the CSS files. This can easily be done in runtime by a tool such as Minify.
Combining resources can be beneficial in that it can reduce the number of HTTP requests; Reducing the number of HTTP requests certainly lowers overhead and can improve performance. It can also have benefits for caching, in that there can be fewer objects in the cache.
That said, this kind of optimization is only useful with metrics. There are profilers out there (Firebug has one) that can show you how many requests you're making and how long they take. You may (or may not) find there are more time-effective ways to increase performance and reduce load on your server.

What is the best way of duplicating an entire website?

I've built a complex site for a client, who wants this duplicated, and re-skinned, so it can be used for other means.
What is the best way of doing this? I'm concerned about copying every file as this means any bugs must be fixed twice, and any improvements must be implmented twice.
I'd look to refactor your code.
Move common functions into a library you can reference from both projects. As you mention that the new site is for a different purpose then you are likely to see divergence and you don't want to hamper yourself later, so extract the common parts and then modify copies (or if appropriate new files) of the remainder to complete your fork.
If you haven't applied good practice already then now is the time to do it and it'll make your work on both sites easier moving forward.
If all the functionality is the same and only the layout is different you could just create a new css file. 2 websites could have exactly the same code base but have different stylesheets and look completely different.
I think that using a version control system like subversion or preferably git, is a good way to duplicate your website. You will be able to track the changes that you make and revert to older versions if things do not work out.
You should implement some kind of instantiation, so look and feel, content and data will be shown depending of what instance of the application is accessed.
In other words, each application access to the code with a different application identifier, meaning content will be served depending on it.
Both application identifier will be pointing to different settings, so stylesheet and content will be absolutely isolated, and both domain will be living in the same IIS application.
If you want to duplicate a whole site it's probably best to copy the whole thing and amend as necessary. Obviously taking great care not to copy large portions of text or else you may be penalised by the search engines.
There are ways you could put the new site onto the same shared host (say within a subdirectory of the original site) and literally 'share' some files. If a unique change is required, you could instead reference a 'local' version of a particular file.
However that sounds like a recipe for a headache to me. I'd prefer to duplicate the whole site. It would be much easier to replace one or two functions on separate websites than it would to try and work out which website(s) are affected by a particular change to your source.

CSS Version Control Idea

I had an idea for "cheap" version control of the css of one of my sites, but am thinking it may not be a good idea. Thought I'd throw it out here in case someone has a similar idea that works better (besides real svn, etc.)
My thought was to create a main css file like "sitename.css" then use #import inside this file to connect to the most recent file with updates. I'd name these imported files by date, eg: 20101222_css.css so I'd know when the last update was applied. When I have a change, I could make my edits, drop the update in the respective location, change the #import to the new file, and viola... updated on the site.
After reading about issues with #import, such as it loading AFTER the page finishes, I'm not too keen on this now.
Any ideas of a way to implement something similar without a full blown system? I do a lot of small project work for various people and thought this method may be a simple way to keep track of things.
Thanks for any ideas/suggestions.
Your idea would add additional page loads to your site for no good reason, which will be a performance hit. It would also expose your versioning to the outside world. And as you say it will suffer from slow loading speeds due to the way #import works.
But the real down-side of this technique is that it only works for CSS files. You haven't solved the problem for any other files on your site.
You seem to think it would be simpler to use than a real SVN setup, but if you end up coming up with different techniques like this for every type of file on your site, you could easily end up giving yourself more headaches than you solve.
SVN is actually quite straightforward to use. With a good GUI (try TortoiseSVN), it's so easy you almost forget its there. Seriously, use SVN. There's no need to come up with 'clever' alternatives.
Its not a good idea, especially if you push this into production. If you want "cheap" version control, download VisualSVN. Its free.
The guys at Yahoo use a technique that reminds me of what you describe:
<link rel="stylesheet" type="text/css" href="http://l.yimg.com/a/combo?arc/yui/reset_2.6.7.css&arc/yui/fonts_2.6.4.css&[....]/subfooter_0.0.12.css" />
It makes sense for them because it's a caching tecnique. They set HTTP headers so stuff never expires: if you load the site one year later and you haven't removed your browser's cache, you shouldn't need to fetch again any of the files that haven't changed.
However, it's by no means a sensible version control system. You already have a good bunch of real version control systems out there!

How do you organize your plugins and themes code?

I starting working with WordPress as a CMS, now that the V3 makes it way easier to manage taxonomies and custom post types. My work is mostly focused on developing plugins and themes.
My biggest plugin does some admin stuff (add admin menu items and the related pages and features), but also does some importing and exporting, and hooks some of the base post processing treatments ("when a new post is created").
My biggest theme is pretty small, and all it does is display custom posts in a custom way.
After a few weeks of work, I have several thousands of LoC, and it's getting harder and harder to dig into it. Which leads me to the following question: How do you organize your WP plugins code? And what about your WP themes code?
several thousands of LoC
That's pretty epic! I've always found the beauty of WP is that I can, as jQuery put it;
Write less, do more!
You might be much better off using Pods CMS alongside WP to cut down your code.
This is how we structure client deployments that include themes, third-party plugins, and custom code.
wp-content/plugins only contains third-party plugins, no code in here is modified, and the site should not be deadlined by any of these plugins being disabled / removed.
wp-content/themes should contain the code related to presentation of the front-end. The trick is not not overload the theme (functions.php and other theme-related files) with code not directly related to presentation.
mu-plugins/ contains all of your implementation-specific business logic. Things in here should never be disabled, and are required for operations.
That is avery brief summary, but in a nutshell that is the logical compartmentalization of code that we've found to be most failure proof.
Why not to split plugin into several files by function? The same goes to themes. Any problem you have with that?
There are basically three ways you can do this: prefixed functions, with require_once's including files by functionality, which is quite common.
The other "right" way that's touted a lot is having one giant class with all your plugin code in it. While keeping things nice, as you said, once that file gets into the thousands of lines of code, you're screwed for manageability.
The way I like to do it is a way coming from my C# background - have one main plugin class, and other "worker" classes (you can put them in a namespace to keep classnames short). For example, have a class dedicated to the admin section (it can have its own little "subclasses" too, say one for each page). It'll take a while to refactor all this code into the different classes and files, but it'll be worth it - it'll be much easier to keep track of everything, as well as for example getting people to work on the codebase together. It also forces you to think more of how your application all fits in together, which lends to better thought out code.
I'm actually writing an article series about this, outlining the three different methods. You can take a look at the first instalment here. There are two more coming in the following weeks.
Hope I helped!

Resources