A picture tag allows us to serve different sized images based on different viewport breakpoints or pixel-ratios, resulting in better page load performance. Google's Pagespeed Insights negatively scores your site if responsive images aren't used. Pretty much all modern browsers support this markup and on the off chance it doesn't, an image fallback can be set.
Using the picture markup inside page templates is pretty straight-forward, but when it comes to CMS related content where HTML editors only accommodate image tags, it's really difficult to get someone like a client to add this form of markup. So the only workaround is to transform any image tag into a picture tag at code-level.
Code: ConvertImageToPictureTag Extension Method
ConvertImageToPictureTag method will perform the following tasks:
- Loop through all image tags.
- Get the URL of the image from the "src" attribute.
- Get other attributes such as "alt" and "style".
- Generate picture markup and add as many source elements based on the viewport breakpoints required, apply the URL of the image, style and alt text.
- Replace the original image tag with the new picture tag.
To use this extension, add this to any string containing HTML markup, as so:
// The HTML markup will generate responsive images using based on the following parameters: // - Images to be resized in 10% increments. // - Images have to be more than 200px wide. // - Viewport sizes to take into consideration: 1000, 768, 300. string contentWithResponsiveImages = myHtmlContent.ConvertImageToPictureTag(10, 200, 1000, 768, 300);
The code I've shown doesn't carry out any image resizing, you will need to integrate that yourself. Generally, any good content management platform will have the capability to serve responsive images. In my case, I use Kentico and can resize images by adding a "width" and/or "height" query parameter to the image URL.
In addition, all image URL's used inside an image tags "src" attribute requires a width query string parameter. The value of the width parameter will be the size the image in its largest form. Depending on the type of platform used, the URL structure to render image sizes might be different. This will be the only place where the code will need to be retrofitted to adapt to your own use case.