css file always loads despite failing to meet medi

2019-09-16 04:03发布

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

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

However, on my 1920px wide screen both chrome and firefox loads mobile.css - it appears to ignore the contents. It just about doubles the amount of time it takes to render the page.

Is there any way to prevent the CSS file from loading if it fails to meet the media query? (I suppose I can live with some .js) Or have I implemented it wrong?

It just seems plain wrong that the browser would load a file and then ignore it.

2条回答
戒情不戒烟
2楼-- · 2019-09-16 04:17

This is what I used in the end. It uses a bit of jquery, but you could convert it away from jquery if you needed to.

First set up the html like this:

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

The data-max is our way of telling the function below to check the max width. When the function is called it will look for elements that have a class called "matchmedia", then test the constraints you specify in data-max and data-min, and should it pass those tests it will make a copy of any attribute whose name starts with "data-" and copy the value across too. And hey presto we have conditional loading.

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);
            }
        }
    }
});
}
查看更多
贼婆χ
3楼-- · 2019-09-16 04:26

I'm afraid that browsers always loads media queries, even if they didn't match. You can read about it in more details here:

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

Also in this article is shown the way to prevent this. In short it will be something like this:

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

Actual article have better ways to include it then document.write, so your should check it out.

查看更多
登录 后发表回答