Using Respond.js when your site CSS is on a CDN or Subdomain

That title is a mouthful.  It better get me more googleability on the Google.  But seriously, I ran into the strangest problem yesterday while trying to put lipstick on yet another pig.  If you haven’t heard of Respond.js then its time to roll out from under your rock.  If you have heard of it, then you know its about the most awesome solution to supporting @media queries (min-width & max-width) on IE8.

What’s this you say?  IE8 doesn’t support @media queries? Nope.  Go ahead, re-size one of your super responsive websites (including Bootstrap) in an IE8 browser, we’ll wait for you to come back.   If you didn’t leave, then you already know.  Response.js solves this problem, and if you’re like me, you don’t really care how.  You just know it’s a well known problem, with a well known solution.  You add the javascript library to your page and VOILA!, IE8 starts to behave.

Respond.js

Big deal you say, I’ve been using that library forever.  I even know all the tricks to make it work when it’s being pesky.  Like including it last, way after all my CSS.  Or including it seperately from Modernizr (sometimes bundling the two together just doesn’t work).  I even know it doesn’t play nice on my local machine, test it on a development server or localhost IIS server, because it’s not going to in a browser from a local file.  One last tip, the one this article is all about.. be careful when using it when your CSS with your @media queries is being hosted on a CDN.   Think that’s a rare occurence, well think again.  In my case, our company setup our own CDN server and starting hosting all our shared CSS and Javascript on it.  In your case you may be using CDNJS (or otherwise) to host your Bootstrap files.   Any way you slice it, if your css that contains your @media queries are on a different domain than your website (yes, even you sub-domains) then you will be bitten by this issue as well.

It all starts with how Respond.js actually works.  IE8 keeps a copy of your CSS it sucks down, but that copy is missing all the tags that it doesn’t understand… like @media.  It just strips them out.  So Respond.js gets around this by smartly requesting a fresh clean copy of your CSS via an AJAX call.  Uh oh.  IE8 and CORS are about to get pissed off.  If your CSS is on a CDN or alternate server from your website, IE8 is about to go all ape sh*t on you and your suspicious AJAX request to a server that is not the same one running the javascript.  Boom.  IE8 may not complain out loud, but you’ll know it’s not working, because that wonderful responsiveness that your @media queries give you is STILL not working in IE8.

Solution time, well there is an official solution, provided by the good folks at Respond.js.  The problem I have with this solution is it is very convoluted and requires many steps to get working.  I have outlined it below.  After you read that, move on and read an alternate solution that I ended up implementing on my site.  Each has it’s PROs and CONs.  Decide which you like and go forth.

Solution 1

The official solution.  Basically it involves a magic gif, some HTML and of course, more javascript:

  • Upload cross-domain/respond-proxy.html to your external domain
  • Upload cross-domain/respond.proxy.gif to your origin domain
  • Reference the file(s) via <link /> element(s):
    <!-- Respond.js proxy on external server -->
    <link href="http://externalcdn.com/respond-proxy.html" id="respond-proxy" rel="respond-proxy" />

    <!-- Respond.js redirect location on local server -->
    <link href="/path/to/respond.proxy.gif" id="respond-redirect" rel="respond-redirect" />

    <!-- Respond.js proxy script on local server -->
    <script src="/path/to/respond.proxy.js"></script>

This worked for me on most sites exhibiting the CDN/X-Domain Respond.js issue.  HOWEVER, it did not work when my website linked to CDN css and local CSS.  The local CSS would cause a new Permission Denied error.  I never did figure this out or find out if it was just me or a common problem.  Because of this issue, and because the above steps seem overly complicated to me, I came up with…

Solution 2

So I figured, if I have to copy all these files, both foreign and domestic just to get this thing working with a CDN, I might as well just create one new file and conditionally include it for < IE9 browsers only.  Simply search through all your CSS for @media and copy and paste every instance you find into a new CSS file.  Include that CSS file conditionally BEFORE your Respond.js include.  Victory.  Too messy for you or wondering what pain that will bring for future updates?  Simply delete your @media queries in every spot you find them and re-locate them entirely to the new file. Then include that new file when bundling your CSS together. That way you don’t have two copies of your @media css floating around, require duel updates and maintenance nightmares.  Either way, the final solution looks something like this:

<!--[if lt IE 9]>
    <link type="text/css" rel="stylesheet" href="../css/my-media.css" />
<![endif]-->

That’s it.  Now Respond.js can get your media queries only from your local server when it needs them.  Even if your main css is on a CDN somewhere.  Mind blown.

 

Erik Runia

Erik Runia

While still a young lad, Erik discovered that learning to program gave him infinite lives while playing Gorillas on a Windows 3.1 machine...

11 thoughts on “Using Respond.js when your site CSS is on a CDN or Subdomain

  1. I just went through the Permission Denied error, and was finally able to get it working by applying two updates that are not in an official release yet.

    Assuming you’re starting with the 1.4.2 branch (not the master), you’ll need to apply the changes from the following commit:
    https://github.com/scottjehl/Respond/commit/7564a2fe204e7d9312c450bae52131da0276733e

    Once that is done, you’ll need to apply the changes from the following open pull request:
    https://github.com/scottjehl/Respond/pull/287/files

    With those two changes, the proxy was able to successfully pull the remote files and ignore the local files.

    Hopefully that pull request will get merged and a new release will get cut, but this’ll have to do for now.

      1. Hi Erik, Did you try Patrick’s code? Success? I tried but was still getting an error.

        Note, I only get permission denied on our company hosted shared file…

        In reading the Respond README, is the problem because I request CSS from two different ‘CDN’ in addition to local CSS? So respond.proxy.html is only working for bootstrap.min.css b/c it is hosted from same CDN?

        In my html source I have the following…

        … // random script files here

        Thanks in advance.

      2. My html didn’t come through..

        In my html source I have the following…

        <link href=”//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css” rel=”stylesheet”>
        <link rel=”stylesheet” type=”text/css” href=”shared/bootstrap-slider.css”/>
        <link rel=”stylesheet” type=”text/css” media=”screen” href=”css/main.css”/>
        <link rel=”stylesheet” type=”text/css” media=”print” href=”css/print.css”/>
        <link id=”mhscriptCSS” href=”//secure.benefittech.com/tools/include/MHScript.4.1.css” type=”text/css” rel=”stylesheet”/>
        <link id=”cssClient” href=”Client.css” type=”text/css” rel=”stylesheet”/>
        … // random script files here
        <script src=”shared/js/respond.js”></script>
        <link href=”//maxcdn.bootstrapcdn.com/respond-proxy.html” id=”respond-proxy” rel=”respond-proxy”>
        <link href=”shared/js/respond.proxy.gif” id=”respond-redirect” rel=”respond-redirect” />
        <script src=”shared/js/respond.proxy.js”></script>

  2. Referring to “just the media-query css example, here are the v-3.3.6 media queries separated for anyone wanting them

    Another approach you could take if you don’t like the separating media queries idea and loading 2 css files for IE8 and below would be this, which will load the cdn version for IE9 and above and all other browsers and the local version for ie8 and below:


    <!--

  3. Проектирование очистных сооружений – это то, на чем специализируется компания «ЭКО». Если вас интересует проектирование очистных сооружений для частного дома, проектирование городских очистных сооружений, проектирование очистных сооружений района, проектирование осадки очистных сооружений, проектирование промышленных очистных сооружений, проектирование очистных сооружений ливневых стоков, проектирование локальных очистных сооружений, то вам нужно обратиться в «ЭКО». Многие жители Москвы и Санкт Петербурга уже оценили обслуживание очистных сооружений, эксплуатацию очистных сооружений, строительство очистных сооружений, расчет очистных сооружений у нас. стоит отметить, что в компании для модернизации, изготовления и проектирования очистных сооружений применяются непременно качественные современные материалы и технологии. Поэтому проектирование очистных сооружений стоков, проектирование биологических очистных сооружений, проектирование очистных сооружений канализации, проектирование сточных очистных сооружений, проектирование локальных очистных сооружений, проектирование осадок очистных сооружений в компании «ЭКО» является обеспечит наилучший результат. Специалисты компании помогут вам со строительством, обслуживанием, проектированием и эксплуатацией очистных сооружений в Москве и Санкт Петербурге, а также других регионах России. Добавим также, что спектр услуг «ЭКО» довольно разнообразен. Это и проектирование ливневых очистных сооружений, и проектирование систем очистных сооружений, и проектирование бытовых очистных сооружений, и проектирование схем очистных сооружений, и проектирование очистных сооружений для автомойки, и проектирование очистных сооружений для дома, и реконструкция очистных сооружений, и очистка очистных сооружений, и установка очистных сооружений.
    ЭКО – Санкт-Петербург: канализация частного дома

  4. Hi,I check your new stuff named “Using Respond.js when your site CSS is on a CDN or Subdomain – Lipstick on the Pig” like every week.Your story-telling style is witty, keep doing what you’re doing! And you can look our website about fast proxy list.

  5. whoah this blog is excellent i really like studying your posts. Keep up the good work! You understand, a lot of persons are hunting round for this information, you could help them greatly.

  6. When I originally commented I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I get four emails with the same comment. Is there a means you can remove me from that service? Thank you!

Leave a Reply to tricia5216 Cancel reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>