Thursday, January 22, 2009

Speed up ASP.NET MVC + jQuery by Combining Files Build-time

The quick answer: Put the following in a file named 'postbuild.bat' in your project root

@echo Combining JS
if EXIST "%~f2Scripts\all.js" del "%~f2Scripts\all.js" /F
copy "%~f2Scripts\*.js" "%~f2Scripts\all.js" /B /Y
 
@echo Combining CSS
if EXIST "%~f2Content\all.css" del "%~f2Content\all.css" /F
copy "%~f2Content\*.css" "%~f2Content\all.css" /B /Y

and run from your project's Post Build Event: $(ProjectDir)postbuild.bat "$(SolutionDir)" "$(ProjectDir)"

Finally, in your site.master, remove all css and js references and simply use 'all.js' and 'all.css'

I recently started using jQuery and MVC on a project for a client, and while I love them, the app just seemed a little sluggish, especially in FireFox.  After some sleuthing, I traced the issue to the 6-7 css and a few .js files being loaded by the app.  This is a well documented problem - each file is a request to the server, and requires overhead on the client and server to serve up. 

Generally, it's better to combine them all into one file.  However doing this by hand makes development more difficult.  One solution is to use HttpHandlers to compress and combine files at run time.  This works, but can be difficult to configure, and executes for every request at runtime. My approach is to combine these all at build-time, so that everything is done as part of the build process. 

In practice, you may need to adjust the paths above.  This combines all js and all css files in the default MVC folders.  If your application is not an MVC app, the same concept will work, but you may need to adjust the folders. 

1 comment:

- said...

nice one, thanks :-)