Remove Respond.js screen flicker

Respond.js makes simple media queries available in older Internet Explorers. It works because it parses the available CSS and saves the media query CSS. After every window resize event the script checks if any of the CSS rules should be applied or removed.

If you develop mobile first and responsive websites than using respond.js is a must. Luckily it’s awesome! But I ran into a problem mentioned by a client today. When used in IE7 and IE8 the browser first shows the mobile version and then quickly shows the correct desktop version. This flicker is quite irritating. So I created a simple hack which solves this. It’s not pretty, but it works.

My solution is to hide the HTML that is affected by the media query to be hidden as quickly as possible by adding a CSS class and than removing it in the media query. As soon as the media query is applied to content is visible again.

After opening the element which contains the content to be hidden (in my case a div with the id “container”) add this javascript. Note that this is HTML5 notation, so add type=”javascript” if needed.

<script>
    document.getElementById("container").className += " hide";
</script>

In your CSS create a new rule.

.hide{
    display: none;
}

Add code which sets the .hide rule to “display: block;” or whatever the default was. It needs to be declared for every “stop” in your responsive design. In my case there was only a mobile (the default) and desktop version. The code in my case:

@media screen and (max-width: 480px){
    #container.hide{
        display: block;
    }
}

@media screen and (min-width: 480px){
    #container.hide{
        display: block;
    }
    /* … rest of your CSS rules … */
}

And that’s it. It’s not bullet proof, but it’s probably water proof. If no javascript is available the content isn’t hidden. It could probably be improved by using Modernizr to check if media queries work and only then apply the javascript, because now the script is alays run.

4 Responses to Remove Respond.js screen flicker

  1. Megan B says:

    Thank you for this!!!!

  2. Dinho says:

    Thanks for this fix. It works perfectly :)

  3. Reeny says:

    Great solution!!!! Thanks.

  4. Robin says:

    This solution is fantastic. I just implemented onto our public web at work and I’m so, so happy that you posted it. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *