Search code examples
htmlcssmime-types

Reference an external CSS file without using the `.css` extension


Is it possible to reference a plain text file as a CSS file within HTML? I have no control over the name or extension of the external CSS file. Take the following as an example:

I have a file called index.html with the following code between the <head> tags:

<head>
    <title>Website</title>
    <link rel="stylesheet" href="https://example.com/styles">
</head>

The external file at example.com/styles looks like this:

body {
    color: red;
    font-family: sans-serif;
    background: blue;
}

If I open index.html I get the following error in my browser's terminal:

The stylesheet https://example.com/styles was not loaded because its MIME type, “text/plain”, is not “text/css”.

Even if I specify the MIME type with type="text/plain" when referencing the styles file, I still get the same error.

Again, I don't have any control over what the styles file is called, or what it's extension is. All I know is it's URL. Obviously this issue could be mitigated by having a web server download the styles file and then give the local copy a .css extension, but for this project I don't have access to a back-end server.


Solution

  • The following achieves what you intend, but is arguably bad practice. It requests the resource and then inserts it in the style tag, bypassing the MIME check by the browser. I would suggest getting the CSS and serving it with correct Content-Type.

    index.html

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>CSS From Text File</title>
      <style id="style"></style>
    </head>
    
    <body>
      <div id="styled"></div>
    </body>
    
    <script>
      const style = document.getElementById('style');
      const req = new XMLHttpRequest();
      req.onloadend = () => {
        style.innerHTML = req.responseText;
      };
      req.open("GET", "style.txt");
      req.send();
    </script>
    
    </html>
    
    

    style.txt

    
    #styled {
      height: 100px;
      width: 100px;
      background: red;
    }