Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditionally display content based on Media Query

I have a website where in the desktop version a sidebar is shown containing 10 to 20 small images. Until now, on mobile devices this sidebar was simply hidden with a display: none, which is the least performant solution since all the images will be loaded anyway.

I'm now wondering what the best way is to disable the sidebar completely on mobile devices (without using a separate AJAX request).

The best solution I could think of is the following:

  • Write the HTML code of the sidebar into a JavaScript variable
  • test the device width by checking a media query with JavaScript (e.g. using Modernizr.mq or so)
  • if this test yields a non-mobile device, write the content of the variable into the DOM, for example by using innerHTML, jQuery.append, jQuery.prepend or similar

I know that RWD performance can sometimes be a very complicated topic and that the most performant solution is often not obvious. So can anyone think of a better solution than the one presented above?

like image 525
m4r73n Avatar asked Nov 03 '22 02:11

m4r73n


2 Answers

If you don't want the images to load on mobile, instead of placing the images as <img> tags, you could set divs to the desired width and height and bring the images in as background images. In your css, hide the sidebar by default. Then, at whatever width you deem to be beyond mobile, use media queries to display the sidebar and load the background images in the divs.

#sidebar {
    display: none;
}
#sidebar div#sidebar-img-1 {
    width: 100px;
    height: 100px;
}
/* ... */

@media only screen and (min-width: 480px) {
    /* display sidebar */
    #sidebar {
        display: block;
    }
    /* set background image for sidebar items */
    #sidebar div#sidebar-img-1 {
        background-image: url("sidebar1.jpg");
    }
    /* ... */
}

The drawback is that by placing content in the stylesheets, you're trading performance for semantics.

like image 129
idahotallpaul Avatar answered Nov 09 '22 05:11

idahotallpaul


I was just doing some research on how to do this and ran into this by the filament group: https://github.com/filamentgroup/Ajax-Include-Pattern/

Seems easy to set up. It works off of what looks like media queries set in data attributes.

So a sidebar you don't want to appear on mobile would look something like this:

<aside href="..." data-append="articles/latest/fragment" data-media="(min-width: 40em)">Possible Mobile Content</aside>

So your sidebar would only come in on a screen that was at least 40ems (~640px) wide. Of course you also need the javascript file and to initiate it, but those look fairly simple as well.

like image 41
Dave Avatar answered Nov 09 '22 07:11

Dave