質問

I am experimenting with conditional stylesheet loading.

I have multiple elements with multiple breakpoints. For each element and each breakpoint I have created a seperate stylesheet. For example:

  • navi-00em-30em.css: one column navigation
  • navi-30em-60em.css: two column navigation
  • navi-60em-inf.css: inline navigation

  • gal-00em-40em.css: one column gallery

  • gal-40em-70em.css: two column gallery
  • gal-70em-inf.css: four column gallery

and so on…

I added these stylesheets to my head-section by using media queries. I defined them to only load in a specific range of width, for example the stylesheet for the two column navigation had these media attributes: screen and (min-width: 30em) and (max-width: 59.999999em).

This technique of course causes many ugly HTTP Requests which leads to lower performance. So I had the idea to detect the screen size via javascript on page load and then load a custom merged CSS file. In our case there would be 5 different files. For example if the screen size would be 50em on page load, gal-40em-70em.css and navi-30em-60em would be merged and appended to the head section. After that the stylesheets which were not merged would be appended to the head section with the obvious media attributes.

How can I do that?

One approach

As I am using enquire.js on the site anyway, I think it is clever to use that script. One possible solution could be (untested!):

query1 = "screen and (max-width: 29.999999em)",
query2 = "screen and (min-width: 30em) and (max-width: 39.999999em)",
query3 = "screen and (min-width: 40em) and (max-width: 59.999999em)",
query4 = "screen and (min-width: 60em) and (max-width: 69.999999em)",
query5 = "screen and (min-width: 70em)";
handler1 = {
  match : function() {
    loadCSS('css/merge.php?q=00em-30em'); 
    enquire
      .unregister( query1, [ handler1,
                             handler2,
                             handler3,
                             handler4,
                             handler5
                           ])
      .unregister( query2, [ … ])
      .unregister( query3, [ … ])
      .unregister( query4, [ … ])
      .unregister( query5, [ … ]);
    }
};
handler2 = {
  match : function() {
    loadCSS('css/merge.php?q=30em-40em'); 
    enquire
      .unregister( … ) …;
    }
};
/* and so on */
enquire.register(query1, handler1);
enquire.register(query2, handler2);
enquire.register(query3, handler3);
enquire.register(query4, handler4);
enquire.register(query5, handler5);

As you can see this is not very slim and I am also not sure if you can nest enquire handlers like I did in my code. Isn't there an easier method?

役に立ちましたか?

解決

OK, found a tool which does this already.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top