Introduction
While we are waiting on a solution to the responsive images problem (current proposal), we still have to take care of the issue in our websites.
This may sound difficult, but in reality, thanks to the work of Scott Jehl, we can emulate responsive images with a simple to use polyfill today. Many other solutions have been created to solve this problem, but I recommend picturefill at the current time because it is similar in syntax to what is currently being proposed and very simple for a novice to install.
To implement picturefill you need a basic grasp of git, javascript, and plain old HTML. That’s it. This whole solution will take you about 5 minutes to get up and running.
Setup
First thing is to grab a copy of the picturefill project from GitHub.
$ git clone https://github.com/scottjehl/picturefill.git
This will create a copy of the GitHub repo on your local machine.
You will want to package this up prior to placing it on your production server. This project contains two files that you will need in your code. First is the picturefill.js file and the second is the external/matchmedia.js. Personally I like to concatenate these files together along with my site Javascript so that I only need one HTTP request to get what I need, but you should do what works in your environment.
The Images
Next you need to assemble the images that you will need. You can have as many as you want based on the breakpoints you need. Personally I like to work with a small, medium and large version of my files, but again, do what works best for your environment.
Include the Javascript
This will be based on your project and how you assembled your Javascript in the Setup portion of this post, but the important thing is that you need to include both the picturefill.js and matchmedia.js file in your page for things to work correctly.
Add the HTML
Your HTML should follow this pattern to work. It’s important that you add in the <noscript> element and keeping with good Mobile First design practice you will want to load the small image first, by doing this you add an element of Future Friendly to your web page. With this code you will now have responsive images, matching a small, medium, or large screen, but if the browser cannot handle Javascript, no problem you fall back to the <noscript> and to be safe we send the small image.
<pre>
<div data-picture data-alt="A giant stone face at The Bayon temple in Angkor Thom, Cambodia">
<div data-src="small.jpg"></div>
<div data-src="medium.jpg" data-media="(min-width: 400px)"></div>
<div data-src="large.jpg" data-media="(min-width: 800px)"></div>
<!-- Fallback content for non-JS browsers. Same img src as the initial, unqualified source element. -->
<noscript>
<img src="external/imgs/small.jpg" alt="A giant stone face at The Bayon temple in Angkor Thom, Cambodia">
</noscript>
</div>
</pre>
You do have other options. Take a look at the documentation for more.