I am currently dynamically loading a background image using the style tag:

<li style="background-image: url({{ project.portfolioImage.first().url }})"> 

I want to add support for retina screens, so I want to also upload a hi-res version as well as the standard one and serve whichever is applicable.

Can I use {% includeHiResCss %} to do that?


This is actually a difficult problem, and there are many possible solutions, none of which are optimal (until img srcsets are better supported).

The way I would probably go about doing this, depends on a couple of factors.

If it is important to show something on load, you need to include an initial image in the markup, like you have already. If that is not an issue, I would include the two different resolutions in data-attributes on the <li>, and then add the appropriate one with Javascript.

It would probably go a little like this:


<li class="js-resp-bg-img" data-low-res="{{ lowresimage.getUrl() }}" data-high-res="{{ highresimage.getUrl() }}">....</li>

js: (not tested, probably needs tweaking to work)

$(function() {
    var windowWidth = window.innerWidth || $(window).width();
    var threshold = 600;
    $('.js-resp-bg-img').each(function(idx, elem) {
        var bgImageUrl = $(elem).attr('data-low-res');
        if (windowWidth > threshold) {
            bgImageUrl = $(elem).attr('data-high-res');
            backgroundImage: 'url(' + bgImageUrl + ')'

If you need something to display on load, you put the low res image in the style tag, and switch it out only when appropriate. Downside with this is you'll load the asset twice.

Also, in my example I'm only testing for window width, if you need to you can do additional tests, for example testing for retina with this method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.