Warning: what you are about to read deals with code.

Working with PHP is fun for me. At times it can be a pain but I still love it. One thing that I have been trying to find is an AJAX media query for loading certain stylesheets when the viewport is at certain widths. I know that it can be achieved but what I’m wondering is how I would pull this off with WordPress.

jQuery makes it easier to achieve since it is a library to help the development process. I know I will begin with that and PHP but the next step will be creating the necessary files.

Of course I want to think mobile first but my dilemma is that would require http requests – to the best of my knowledge. The good side about that is that yes it would load the needed stylesheet and won’t do any browser sniffing so it relies on the viewport and resolution of the device.

On the plus side I can pretty much start it fairly quickly with a simple jQuery call.

$( window ).resize( function(){
  var width = $( window ).width();

    if ( width < 640 ){
      // Load this stylesheet
      } else if ( 641 < width < 800 ) {
      // Load this stylesheet
      } else {
      // Load this one
      };
});

Now what this really does is check when the screen is resized and not really for the initial width which is what I need to check for. So, what I really need is to first check the width and load the stylesheet accordingly and if the window gets resized run that same check. So I can create a new self invoking function and see how that would work.

var w_check = (function(){
  if ( width < 640 ){
      // Load this stylesheet
      } else if ( 641 < width < 800 ) {
      // Load this stylesheet
      } else {
      // Load this one
      };
})();
$( window ).resize( w_check() );

But then I run into the issue of having more than one stylesheet opened at once and risking the theme getting all warbled. 😐 Yes, they would still have media queries but can I safely use all at once without hurting the layout? I think I may just have to test this out before I deploy. Notepad++, here we come!!