Stefan Ledin

My Picturefill plugin for WordPress

The performance of a website is something that I’m very interested about. Especially when it comes to mobile, which of course is something very important to care about these days.
The biggest bottleneck tends to be images. Large and many images.

You can follow all the best practices that’s out there and concat and minify all of your scripts and stylesheets. But as soon you add a couple of big images, the site will feel slow anyway.
Images that are 1440 pixels wide don’t belong in the DOM on an iPhone with a screen that is 320 pixels wide. The solution to this problem is of course responsive images.


The <picture> element is on it’s way and has recently been implemented in Chrome Canary. However, it’s gonna take some time before we can rely on and the srcset/sizes attributes.
Until then, Picturefill is a great polyfill that enables support for these features. Version 2 is currently in beta and will allow the use of the <picture> element. In version 1, <span> tags were used instead.

Get to the point!

Before I started to see any signs of Picturefill 2 on Twitter, I began developing a plugin for WordPress that helped generating the required markup for Picturefill (1).
For example, it replaces something like:

<img src="" alt="Image description>

…with the following code:

<span data-picture data-alt="Image description">
    <span data-src=""></span>
    <span data-src="" data-media="(min-width: 150px)"></span>
    <span data-src="" data-media="(min-width: 300px)"></span>
    <span data-src="" data-media="(min-width: 480px)"></span>
    <span data-src="" data-media="(min-width: 880px)"></span>
    <span data-src="" data-media="(min-width: 1024px)"></span>
        <img src="" alt="Image description">

A filter on the_content accomplishes this. But that’s not all the plugin can do. You can also use it inside your templates. This snippet will create something like the code above:

<?php echo Picture::create( 'element', $attachment_ID ); ?>

You might wonder why you need to specify that it’s an element that should be created? The reason is that you also can use the plugin to generate CSS.
Let’s say that you have a large header containing a big background image. The administrator of the site has the ability to change the image, so you need to write some inline CSS to make it work.
This snippet will take care of that:

echo Picture::create( 'style' , $attachment_ID, array(
    'selector' => '#header'

This is the output:

#header {
    background-image: url("");
@media screen and (min-width: 150px) {
    #header {
        background-image: url("");
/* And so on... */

Pretty neat, don’t you think?

Picturefill 2

I’ve been thinking about releasing the plugin on, but I want to implement the new version of Picturefill first.
I also need to come up with a good name for the plugin. That might be the hardest part.
For now, the plugin is located at this repository on GitHub.
To be continued!