The Surrican
The Surrican

Reputation: 29866

Is it possible to reference external stylesheets in the html body?

I want to external CSS files side by side of html code in the body.

Why?

I am developing some templates that get included inside a page, but from those templates I cannot modify the head or add JS/CSS references to the html head section.

What I currently have is:

<html>
<head>
<!-- this i cannot edit -->
</head>
<body>
<!-- some html code -->
<!-- now comes what i can edit --> 
    <style>
    #mywidget {
     color: red;
    }
    </style>
    <div id="mywidget">
    hello
    </div>

<!-- end of section i can edit -->
<!-- other html code -->
</body>
</html>

I would like turn that into something like:

<html>
<head>
<!-- this i cannot edit -->
</head>
<body>
<!-- some html code -->
<!-- now comes what i can edit --> 

    <!-- LINK TO AN EXTERNAL CSS FILE -->

    <div id="mywidget">
    hello
    </div>

<!-- end of section i can edit -->
<!-- other html code -->
</body>
</html>

But I dont want the overhead of loading all the css every time the page loads, so i want to put it into an external file.

I thought of loading the external css (it will be hosted within the same domain) using javascript, then create a element and insert the content somehow...

I think this should work, however if not I think I can hack some style parser together using jquery which applies the styles at least for basic definitions.

But I am sure there must be a better way!

Any hint is appriciated!

Upvotes: 2

Views: 2556

Answers (3)

Pevara
Pevara

Reputation: 14310

putting style tags inside the body is indeed invalid according to html standrds (though it might work in some browsers)

you can put script in the body though, and you can make the script insert the style link in your head. jquery pseudocode would look like this

<body>
  ...
  <script type="text/javascript">
    $(document).ready(function() {
      $('head').append('<link rel="stylesheet" type="text/css" href="style.css">');
    });
  </script>
  ...
</body>

Upvotes: 3

Zaq
Zaq

Reputation: 1348

<link rel="stylesheet" type="text/css" href="style.css">-- you can put this in the <body> tag, too; it works just fine in chrome.

Upvotes: 1

Adi
Adi

Reputation: 5179

You can use CSS's @import rule

<style type="text/css">
  @import url("external.css");
</style> 

Upvotes: 4

Related Questions