Pages

Wednesday, October 31, 2012

Optimizing image loading in MVC VS-2012 websites

Images often take up a large proportion of the load time of a webpage, second only to data retrieval from a database. Here are 3 things we can do in our Visual Studio MVC website projects, to significantly reduce that load time.

  1. Reduce file size, by controlling the image dimensions and its jpeg quality. Ideally, images should be of exactly the dimensions (width and height in pixels) that are to be finally displayed on the webpage (typically controlled by the css img width and height properties). Also, reducing the jpeg quality (increasing compression) a little may result in a drastic drop in file size while still having very good screen-display quality. If you are using the EncoderParameter class to process images for uploading, consider using a compression level of 90.
  2. Enable image caching at both server and browser levels. Use the OutputCache attribute on your controller action method that retrieves the images, and set its location property to "ServerAndClient". The duration property can be set appropriately depending upon your website, and will determine how long your web server and the user's browser are going to cache the image. Added bonus: The server caching will reduce your storage data-out costs, and the browser caching will reduce your web server data-out costs.
  3. Eliminate duplicate pulls of the same image, by always using an identical method call pattern. Parameters in an action method are not case-sensitive, nor do they need all the parameters to be included in a call (missing parameters will receive a null). However, when retrieving the same image from different pages or different parts of the same page, inconsistency in the calls from your .cshtml or .vbhtml files will cause your browser to consider these as separate elements, and it will send multiple requests to your server. If the calls are identical, most browsers will send only a single request, and will then cache and re-use the same image. Recommendation: In your @Url.Action() calls, make sure to specify all of the action method's parameters, and treat them as though they were case-sensitive.
Using the above 3 suggestions, you should see significant load time improvements. A good way to do a quick (but pretty detailed) check of the page's performance in the Google Chrome browser: Right-click on the page | click on Inspect Element | click on the Network tab | refresh your page. You'll see exactly what was loaded, and how long each element took. You can click on the Images tab at the bottom, to examine just the images. Then tweak your website using the above suggestions - and look out for improved performance and happier users!

Happy coding!

No comments:

Post a Comment