One of the nice features I like about MVC3 is the addition of a module that one can use to create and use sprites on a website.. but I think I will need to go back a little bit and say what a sprite is.
Ah.. no, it is not the soda that Fido Dido once endorsed. Not that kind of sprite.
A sprite is a solution, or way to speed up websites. A lot of(if not all) websites use images. And these images really have a negative impact on performance. Imagine if you will, a navigation menu with 12 image buttons. Each image button, if a rollover effect is added, and an on_click effect, would have a total of.. well a lot. Each one will need a trip to the server (a request) and that will take time.
So, what the industry has been doing now, is creating a large image with all the needed images as a composite then dumping that to the site. Then CSS comes in and gets only portions of the composite image and uses that. This way, all the images will be loaded with only one trip.
Here is a sample of an image that can be “sprited”
This is all good BUT.. as you can see, adding a new image to this sprite will be cumbersome at the least and we all know how lazy we are :p
Good thing some guy (probably a Canadian) in Microsoft added this functionality as part of MVC3.
All we need to do now, is add a folder in our project called “asp_sprites”, dump all the images there, and use them. .Net will automagically create the composite image.. and all the needed CSS properties to use these images as sprites! Awesome!
But wait! There’s more!
MVC3 also has the option of adding the image as a base64 encoded string so you won’t really have a real image file but the image as a string.
Okay okay! How to do it.. here..
add a few things to your project.
1. a folder named “asp_sprites” andput your images there
2. add a reference to ImageOptimizationFramework and ImageSprite dlls. If you don’t have these DLLs, look them up on codeplex.
3. Add this to web.config
<httpModules> <add type="Microsoft.Samples.Web.ImageOptimizationModule" name="Microsoft.Samples.Web.ImageOptimizationModule"/> </httpModules>
4. ahhmm.. no more!
Now instead of going
<img src="/app_sprites/image1.png" /> <a href="#">Link to somewhere</a> </li> <li> <img src="/app_sprites/image2.png" /> <a href="#">Link to somewehre else</a> </li> <li>
@Microsoft.Samples.Web.ImageSprite.Image("~/App_Sprites/image1.png") <a href="#">Link to somewehre</a> </li> <li> @Microsoft.Samples.Web.ImageSprite.Image("~/App_Sprites/image2.png") <a href="#">Link to somewhere else</a> </li>