Escolar Documentos
Profissional Documentos
Cultura Documentos
Morgan McLean
in ASP.NET
How to use built-in support for CSS sprites and base64 image inlining to
make your site load images faster
Figure 1: Pages on the Northwind Online site include a large number of small images.
Without image optimization, these images would cause page to load slowly as the browser
requests each image individually.
Most browsers and web servers are configured to allow anywhere between two to
six HTTP connections at a time. This causes the HTTP request latency to
significantly impact the amount of time that it takes to load a web page that
contains many images, because only a limited number of requests can be
processed in parallel, as shown in Figure 2:
Figure 2: A partial analysis of the time spent loading a popular technology news site. The X-
axis is the running time, and each piece of content is given its own horizontal series.
The graph in Figure 2 shows how inefficiently most web browsers download image-
heavy pages. On each data series, the light purple section displays the latent time
required to initiate each download, while the smaller dark purple segments
indicated the actual download time. Additionally, there is a limitation on how many
downloads can take place at the same time, which defeats the possible advantages
of many images loading in parallel. The grouping of smaller image downloads in the
red circle shows how this limitation is particularly wasteful, because each download
spends more time waiting for an HTTP response than actually streaming the image
data.
You can see that reducing this inefficiency can provide large benefits in terms of
reduced time waiting for pages to load. It can also diminish the load on the content
provider’s server and network as well, because the reduced number of HTTP
requests lessens the work for load balancers.
Sprites
A sprite is a collection of graphics combined into a single image file, from which you
can extract individual images using their grid location and size. Using sprites
instead of collections of discrete images goes back to the era of 8-bit video games,
where programmers found that by merging all of a game’s individual bitmaps into a
single grid-style file, they could significantly reduce the amount of memory required
Figure 3: An example of a sprite sheet from an 80’s style game. By combining many small
images into a single file, programmers were able to save significant amounts of memory.
(Figure credited to The Sprite Artists of Game Design Novice.)
After the page and sprites have been downloaded to a browser, the browser can use
the individual images in the sprites through settings from the CSS background-
position, width, and height descriptors. These settings let you slice an individual
image out of a sprite sheet, which is referenced as the value of the CSS
background-image property. The following figure shows CSS rules that include
background-image descriptors. Notice that in each case the descriptor points to
the same image, url(sprite0.png), which is the sprite that contains the combined
smaller images. However, each rule includes distinct dimensions for background-
position, width, and height settings.
You can work around all of these limitations except browser support. To offset the
expansion factor of using base-64 encoding for images, you can use server-side gzip
compression.
To avoid duplication and to enable caching, you can store the encoded images in
CSS files (in groups, just as with sprites). The following example shows the CSS
class definition for an inlined image that is similar to that of a sprite, differing only
in the lack of a background-position property and the URL used for the
background setting:
.dotNet-png
{
width:310px;
height:155px;
text-decoration:none;
display:block;
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAATYAAACb…
}
Images inlined through CSS are referenced by associating a class name with an
HTML element, in the same way that you reference images from a sprite collection.
Moderate file size Small file size; images Larger file size due to
save space when packed base-64 encoding
together
Browser Compatibility
• Fewer performance gains. The large size of content images reduces the
ratio of time spent downloading an image versus the time wasted on HTTP
request latency. Therefore, these optimizations will not significantly increase
the performance of a site if used for content images.
• SEO and discoverability. Images referenced through CSS are interpreted to
be background elements by web browsers and search engines. Therefore,
sprites and inlined images are ignored by web crawlers.
• Poor accessibility. If a page containing optimized images is read through a
screen reader or displayed in a browser’s accessibility mode (which typically
disables CSS), the images will not appear. In addition, the open space that
would normally be reserved for a missing image will not appear, which could
possibly break the page’s formatting.
• No alternative (alt) text. Because inline and sprite images are background
images, they do not support alternative text. This affects accessibility (see
previous point) and does not let you add text that in some browsers is
displayed as a tooltip.
Figure 6: Assemblies required in order to use the ASP.NET image optimization framework.
IIS 6
<httpModules>
<add type ="Microsoft.Samples.Web.ImageOptimizationModule"
name ="Microsoft.Samples.Web.ImageOptimizationModule"/>
</httpModules>
IIS 7
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add type="Microsoft.Samples.Web.ImageOptimizationModule"
name ="Microsoft.Samples.Web.ImageOptimizationModule"/>
</modules>
</system.webServer>
At run time, the images in each subfolder are automatically merged into sprites or
inlined directly into CSS files (which are created by the optimization package),
depending on how you have configured them. (See the next section for more details
on how to configure settings).
• FileFormat. This controls the image format of the final sprite. Options are
JPG, GIF, PNG, and BMP.
• Quality. This controls the level of compression performed during the creation
of the sprite for image formats that support this parameter. The value is
specified as an integer that represents compression percentage.
• MaxSize. This determines the maximum size (in KB) for sprite images. If the
combined size of the images in a sprite folder exceeds this value, multiple
sprites will be created automatically and referenced transparently through a
single CSS file.
• BackgroundColor. This defines the background color of the sprite image
(including transparency), specified in standard ARGB format. This setting is
typically used when you add transparent PNG images to a sprite that will be
saved in a format that does not support transparency.
• Base64Encoding. This enables or disables base-64 format for inlined
images. (Even if this is enabled, sprites will be produced for compatibility with
browsers that do not support inlined images.)
<img class="aspNetLogos_2-png"
src="data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEA
AAICTAEAOw==" />
To ensure compatibility across all browsers, the image optimization framework
generates two CSS files: highCompat.css, which allows the use of inlined images (if
you enabled this option), and lowCompat.css, which will only render sprites.
In order for the CSS reference to work correctly, the correct style sheet must be
linked in the page’s head section. The following example shows a link to the style
sheet that is compatible with all browsers (that is, that renders using sprites):
<SpriteImage:SpriteImage ID="SpriteImage3"
runat="server"
ImageUrl="~/App_Sprites/aspNetLogos/2.png"
Optimize="true" />
You set the ImageUrl property to the unoptimized source image in the App_Sprites
folder that you want the control to display, and set the additional Optimize
property to true. When the page is rendered, the image optimization framework
adds the appropriate CSS link to the page’s header, and renders an img element
whose class attribute that points to the appropriate CSS definition for the optimized
image.
To insert images into a view or Razor page, use the ImageSprite.Image helper as
in the following example:
<link href="App_Sprites/subFolderOne/subFolderTwo/lowCompat.css"
rel="stylesheet"
type="text/css"
media="all" />
If your site will be visited by users who might use different browsers, it is
recommended that you link to the low-compatibility CSS file (which enables sprites,
but not inlining), because most web browsers do not display inlined images. If you
can safely predict that your users will have browsers that support inlined images,
you can link to the alternative CSS file.
You can then reference an optimized image through a CSS class, using a class name
that is generated based on the path of the source image file relative to the
App_Sprites folder. Because the “/” and “.” characters are reserved in CSS
definitions, they are converted into “_“ and “-“, respectively, when the class names
are generated by the framework. For example, an image might be stored at the
following path:
~/App_Sprites/subFolderOne/subFolderTwo/myImage.png
subFolderOne_subFolderTwo_myImage-png
You can associate the class with a variety of HTML elements, including the inlined
one-pixel transparent GIF discussed earlier, using syntax like the following:
<img class="subFolderOne_subFolderTwo_myImage-png"
src="data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEA
AAICTAEAOw==" />
Static Fields
HighCompatibilityCssFi
The name of the CSS file used for browsers that are able
le to use inlined images.
LowCompatibilityCssFil
The name of the CSS file used for browsers that do not
e support inlining.
InlinedTransparentGif
The base-64 encoded string for a single-pixel inlined GIF
image.
SettingsFileName
The name of the file used to override a directory’s image
optimization settings.
TimestampFileName
The name of the file used to check if a directory needs to
be rebuilt on application start.
Public Methods
AddCacheDependencie
Adds cache items to the specified directory and all of its
s subdirectories.
IsOutputSprite
Returns true if the path parameter points to a sprite file
produced by the framework or to a CSS file.
LinkCompatibleCssFile
Returns the name of the CSS file that the current browser
is able to support, or null if the browser cannot support
any optimizations.
MakeCssClassName
Generates the CSS class name used by the framework to
reference an optimized image. The path parameter must
be a subdirectory of App_Sprites.
The information contained in this document represents the current view of Microsoft
Corporation on the issues discussed as of the date of publication. Because
Microsoft must respond to changing market conditions, it should not be interpreted
to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the
accuracy of any information presented after the date of publication.
Complying with all applicable copyright laws is the responsibility of the user.
Without limiting the rights under copyright, no part of this document may be
reproduced, stored in or introduced into a retrieval system, or transmitted in any
form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft
Corporation.
The names of actual companies and products mentioned herein may be the
trademarks of their respective owners.