The css file is always loaded, despite the fact that it does not match the media request

I have the following stylesheet link code inside my index.html document:

<link href="static/css/mobile.css" rel="stylesheet" media="screen and (max-width: 739px)"> 

However, on my widescreen 1920px screen, both chrome and firefox load mobile.css - it seems to ignore the content. This roughly doubles the time it takes to display the page.

Is there a way to prevent the CSS file from loading if it doesn't respond to media requests? (I suppose I can live with some .js) Or did I do it wrong?

It just seems wrong that the browser will download the file and then ignore it.

0
html css media-queries
source share
2 answers

I am afraid that browsers always load media requests, even if they do not match. You can read more about this here:

http://christianheilmann.com/2012/12/19/conditional-loading-of-resources-with-mediaqueries/

This article also shows a way to prevent this. In short, it will be something like this:

  • Test request with JS, not CSS: window.matchMedia('screen and (max-width: 739px)'); .
  • Then, if it matches, you add your CSS with something like: document.write('<link rel="stylesheet" href="small.css">');

In a real article, there are more efficient ways to include it, then document.write , so you should check it out.

+2
source share

This is what I used at the end. It uses a bit of jquery, but you can convert it from jquery if you need to.

First configure html as follows:

 <link class="matchmedia" data-href="static/css/mobile.css" data-rel="stylesheet" data-max="739"> 

Data-max is our way of reporting the functions below to check the maximum width. When a function is called, it will look for elements that have a class called "matchmedia", and then check the restrictions specified in data-max and data-min, and if they pass these tests, it will make a copy of any attribute whose name begins with "data-" and copy the value. And hey presto we have a conditional load.

 ws.width = <your favourite method of getting the width>; function mediaMatchHTML() { $(".matchmedia").each(function(){ var min = this.getAttribute("data-min"); //in pixels var max = this.getAttribute("data-max"); //Check condition if ((min === null || ws.width >= min) && (max === null || ws.width <= max)) { for (var c=0; c<this.attributes.length; c++) { var name = this.attributes[c].name.slice(5); if ("data-"+name == this.attributes[c].name) { //is this lined up for conversion? this.setAttribute(name, this.attributes[c].value); } } } }); } 
0
source share

All Articles