简体   繁体   中英

Convert external CSS stylesheet into inline styles, or into a <style> tag, via Javascript

I need to get the whole HTML document complete with CSS styles without actually using the external CSS files.

For example I need this...

index.html

<head>
    <link rel="stylesheet" href="css/styles.css">
</head>

<body>
    <div id="foo">Test</div>
</body>

css/styles.css

#foo {
    color: red;
}

...converted into something like either of the ff, so that:

1) all the styles in the external CSS are inline-d into the elements

index.html

<head>
    <link rel="stylesheet" href="css/styles.css">
</head>

<body>
    <div id="foo" style="color:red;">Test</div>
</body>

OR

2) the styles are inline-d into a <style> tag

index.html

<head>
    <link rel="stylesheet" href="css/styles.css">
    <style>#foo { color: red; }</style>
</head>

<body>
    <div id="foo">Test</div>
</body>

Is that doable in vanilla Javascript/jQuery? Thanks.

I have a solution for second case. Use ajax call to get the file content as string and append dynamically created style tag in the document

var css = '.popover { background-color: #666666; color: #ffffff';               
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}
head.appendChild(style);

In the vanilla JavaScript you can simply make an HTTP request to get the content of the css/styles.css file and then create a new style element. Something along these lines:

var head = document.head || document.getElementsByTagName('head')[0],
  xhttp = new XMLHttpRequest();

xhttp.open('GET', '/css/styles.css');
xhttp.onreadystatechange = function() {
  if (xhttp.readyState === 4) {
    if (xhttp.status === 200) {
      var style = document.createElement('style');
      style.type = 'text/css';
      if (style.styleSheet) {
        style.styleSheet.cssText = xhttp.responseText;
      } else {
        style.appendChild(document.createTextNode(xhttp.responseText));
      }
      head.appendChild(style);
    } else {
      console.log("Error", xhttp.statusText);
    }
  }
}
xhttp.send();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM