FlipFloop
FlipFloop

Reputation: 1264

Can we use the media property in HTML while linking to a Javascript file?

I know that when we link CSS files in HTML, we can use media to load different Stylesheets depending on certain things, can we do this while linking to scripts? Here is my HTML:

    <link rel="stylesheet" href="stylesheet/main.css" />
    <link rel="stylesheet" href="stylesheet/style.css" media="(min-width: 808px)" type="text/css" />
    <link rel="stylesheet" href="stylesheet/mobile.css" media="(max-width: 807px)" type="text/css" />
    <script media="(min-width: 808px)" src = "scripts/script.js"></script>
    <script media="(max-width: 807px)" src = "scripts/mobile.js"></script>

Will this work?

Upvotes: 0

Views: 38

Answers (2)

Sumit Sahay
Sumit Sahay

Reputation: 514

You can write like this:

var winCurrWidth = $(window).width();

If window resize happens, just add:

$(window).on('resize', function(){
   winCurrWidth = $(window).width();
});

Now start wirting like this:

if(winCurrWidth < 808){
  //Do Something..
}
else{
  //Do something else..
}

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074495

No. The specification for script doesn't list media as one of the supported attributes. And if you think about it, for that particular example, what is the browser supposed to do if, after loading the page when the width was 850px and running the script.js file, the user resizes the window to 600px wide? It can't undo what script.js did.

But if you were testing for something that wouldn't change, you could use window.matchMedia to determine which script to load dynamically. (Reasonably supported, including the last several releases of iOS Safari and Android's built-in browser and the latest release of most mobile browsers, but not IE9 or earlier, or Opera Mini.)

Upvotes: 2

Related Questions