C.O.
C.O.

Reputation: 2329

How to change the media attribute of a css file with plain JS

To avoid blocking the rendering of the "above the fold content" of a site one options seems to be using a css file with a bogus media. Browsers will download it asynchronously anyway as the media "could" apply later...

<head>
    <link rel="stylesheet" href="style.css" media="bogus">
</head>

Now, one way to get the CSS in place would be a link (with the proper media screen) at the very end of the body tag but i'd rather look at JS options.

Question: How do we change the media bogus using plain JS (no jQuery, no frameworks)

Upvotes: 1

Views: 977

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

These are the steps you can follow:

  1. Add an id to the <link /> tag.

    <link rel="stylesheet" href="style.css" media="bogus" id="myLink" />
    
  2. Use the following JavaScript (either one of the lines):

    document.getElementById("myLink").setAttribute("media", "screen");
    document.querySelector("#myLink").setAttribute("media", "screen");
    document.querySelectorAll("link")[0].setAttribute("media", "screen");
    

My recommendation is to better add an id and then call using it.

Upvotes: 3

Related Questions