ASP.NET - script and css compression - asp.net

Is there any native compression (for javascript/css files) available in ASP.NET?

Try Chirpy. It mashes, minifies, and validates your javascript, stylesheet, and dotless files.
You can use YUI Compressor or Google Closure Compiler.
http://chirpy.codeplex.com/
Or, for more info, check out:
http://www.weirdlover.com/2010/05/22/visual-studio-add-in-for-dotless-js-and-css-files/

In the appendix of Professional ASP.NET 3.5 Scott Hanselman talks about Packer for .NET. This will integrate with MSBuild and pack javascript files for production deployments etc.

You could use Packer.
This utlity supports JavaScript compression and /or "minifying", and CSS "minifying".
It's available as a command line utility or also as an MSBuild task.
This way you can integrate it into your build process / Visual Studio project.

There is Gzip/Deflate compression support in IIS compatible with all modern browsers except IE6. For IIS 7 check this page: http://www.iis.net/ConfigReference/system.webServer/httpCompression

Further to other answers and comments, you can use Yahoo!'s YUI Compressor and make it an MSBuild Task to integration it into your build and deployment process.

Try StyleManager for CSS combination and minification. It uses YUI Compressor under-the-hood.
Its usage is a lot like asp.net's ScriptManager, so it's quick to get used to. It's easy to add to your project too, only takes a minute.
Most importantly - it combines your CSS files too. So instead of having like 10 CSS files to download it'll just be 1, which will also be compressed etc.

I have written something to do this for me, you can download it here:
http://www.picnet.com.au/blogs/Guido/post/2009/12/10/Javascript-runtime-compilation-using-AspNet-and-Googles-Closure-Compiler.aspx
It uses Google's closure compiler which is pretty awesome.
Thanks
Guido

Here is my way:
Use MVC.
Process js|css content via MVC controller's actions.
Combine multiple files into one.
Minify and obfuscate script|css on fly before it stored in cache.
Cache results.
Use CacheDependency.
Enable gzip for dynamic content.
Enable gzip before cache feature.
Everything can be done just by adding custom attributes on action methods, using ASP.NET MVC Js/Css Composer/Compressor.
Sample:
public class JsController : Controller
{
[Utility.Processors.JsCompress]
[OutputCache(Duration = 3600)]
public ActionResult Jquery()
{
return View();
}
}
You can derive from CustomTextPostProcessingAttribute and make your own postprocessing for any type of text content, you need.

I just learned something today: you can run JavaScript via windows console. I'm a fan of cssmin.js; so, this plus windows console = win! All you have to do is download cssmin.js, put it in a folder on your web project and add the following post-build event in Visual Studio:
type "$(ProjectDir)css\*.css" | cscript //NoLogo "$(SolutionDir)tools\cssmin.js" > "$(ProjectDir)css\core.min.css"
Doing this keeps you from having to edit your project as ajaxmin would have you to do.

Related

symfony 2 REST and JS (ember.js) client

I made a simple REST API bundle with Symfony 2 and now i want to use ember.js as a client.
I made a new bundle for it (ClientBundle). Where should i put the js files? Into
the ClientBundle/Resources folder under public/js?
app/web under public folder
somewhere else
what is the best practice / your favourite folder structure?
The best practice is to put the client code into a separate repository and use JS specific tools for its development.
Just because you can put them into a single repository doesn't mean you should. Imagine what a mess that repository will become if/when you add other clients like Android, iOS, and so on.
We put the client JS under Bundle/Resources/public/ and have a separate frontend and backend bundle. We just published a sample distro to show how this is organized here:
https://github.com/ucsf-ckm/symfony-emberjs-edition
Currently the answer would be to store the assets in the /web directory. Source
If you intend the ClientBundle to be reusable across different projects you may have, you are best served by placing the files into the ClientBundle\Resources\public\js folder.

ASP.NET Bundling: Run IBundleTransform even when not optimizing

We're using System.Web.Optimization bundling to bundle & compress our JS and CSS.
We also use a custom IBundleTransform implementation in addition to to the existing JsMinify and CssMinify to do some fancy stuff to the JS (replacement of certain placeholders) before sending it to the browser.
Everything works fine as long as we're running in Release mode, because then the bundling and optimizing kicks in. But in Debug mode (which is nice for debugging ;) it seems to completely ignore all the specified IBundleTransform (makes sense in most use-cases, I guess).
Is there any way to always run our own IBundleTransform, even in Debug mode, but run the other (default) bundling algorithms (JsMinify, CssMinify) only when I really want to optimize (in Release mode)?
So the debug/release magic is controlled via the Scripts/Styles helpers. The behavior to not apply any transforms is baked into the implementation of these helpers, so if you want to do this, the best workaround might just be to have a debug/release version of each bundle and always enable bundling via BundleTable.EnableOptimizations = true.
if (!HttpContext.Current.IsDebuggingEnabled)
BundleTable.EnableOptimizations = true;

Microsoft ASP.NET Web Optimization Framework 1.0.0 debug mode error

I have two questions, one about a bug and one about cdn
QUESTION 1: (BUG)
I have just added the new NuGet package: Microsoft ASP.NET Web Optimization Framework 1.0.0.
I'm using ASP.NET MVC 3, and everything seems to be working except for one major bug.
If I use debug="true" in web.config, then no script tags ever get outputted. I checked the view source and there are no tags for that bundle at all.
If I set debug="false" then I get the script tag that points to my minification file.
*Is this a bug? Has anyone else experienced that? *
As a workaround so that I'm at least able to debug my application, I forced optimization on regardless if I'm in debug mode or not BundleTable.EnableOptimizations = true;
QUESTION 2: (CDN)
Also another question I have is about the CDN Support:
bundles.Add(new ScriptBundle("~/bundles/jquery",
jqueryCdnPath).Include(
"~/Scripts/jquery-{version}.js"));
If I want to add another script with CDN support, then I would have to add another bundle, therefore if UseCdn="false", then it will try and load up 2 scripts separately, meaning 2 requests. Is there any way to have CDN support for multiple scripts so that it will combine them into 1 request if UseCdn="false"?
Something like this:
bundles.Add(new ScriptBundle("~/bundles/multiple").Include(
"~/Scripts/jquery-{version}.js", jqueryCdnPath,
"~/Scripts/jquery-ui-{version}.js", jqueryUICdnPath,
));
Regards DotnetShadow
Could you expand on what isn't working on in your MVC3 app, i.e. how are you using the Scripts/Styles.Render methods?
In regards to #2, currently the CDN support is only on a per bundle basis. So you will not be able to do the conditional bundling that you want and use cdn (unless you had access to a CDN which you could upload new content to, then you could just upload your bundle to the CDN)

using SquishIt with web resources

I'm using the SquishIt to manage the js/css files and it works perfect, but only with my manually created files. How can I use it with the asp.net webresources/script resources (scripts for ajax, validation etc.) which are returned to browser throught the script manager?
A method on bundles called .AddRootEmbeddedResource has been added to deal with situations like this (where an embedded resource does not use the default AssemblyName.ResourceName convention)

Passing build timestamp to code

I would like to give my CSS and javascript files far-future headers and add a token onto the URLs referrring to them. That way browsers don't have to re-download CSS and javascript unless I've released a new build of the site.
http://example.com/css/styles.css?build=23424
How can I pass a build number or timestamp to my code-behind so it can add the timestamp?
Obviously C# doesn't have macros, which is what I would use in C/C++.
I realise that this will force browsers to download assets whenever I do a new build - regardless of whether or not the build involved changing the assets. However, I would like to put a simple scheme in place before I implement anything more advanced like looking at individual file modification times.
Here's a bit of code that I use to extract the build id from the current assembly at application start. It reads the version number from the assembly, a version designator (dev/qa/blank) from the web config, then constructs a version number string to stuff into the application. This code goes in Global.asax.cs. You can then refer to it in your markup from the Application instance.
var webAssembly = Assembly.GetAssembly( typeof(...known class...) );
var designator = WebConfigurationManager.AppSettings["VersionDesignator"];
string version = webAssembly.GetName().Version + designator;
this.Application.Add( "Version", version );
Here's an example of how you could use it in an MVC context (sorry I don't have any WebForms examples).
<link type="text/css" rel="stylesheet"
href="/Content/styles/screen.css?build=<%= this.Application["Version"] %>" />
Interesting idea.
Here's one way to do it:
Go into your AssemblyInfo.cs class under the Properties folder in your project.
Change your assembly version to include the star wildcard: [assembly: AssemblyVersion("1.0.*")].
In your code, you can retrieve the current build version like this:
_
var buildNumber = Assembly.GetExecutingAssembly().GetName().Version.Build;
_
That's it, you're done.
Changing the AssemblyVersion to 1.0.* will cause Visual Studio/MSBuild to increment the build number automatically for you each build. Then, you can access this build number at runtime using the above code snippet. Easy as cheese.
Browsers and servers know how to handle caching via HTTP. So, I misunderstand, what are you trying to accomplish with providing this kind of caching. A browser will not re-download your CSS and Javascript if it has seen it recently. And it will re-download it if you do a push of your new build on the server. See cache headers like Cache-control and Expires etc. Here's a tutorial http://www.mnot.net/cache_docs/

Resources