2

I have a web page in which I add a css file in head section using javascript code from the bootom of the page:

$(document).ready(function(){
var css=document.createElement('link');
css.type='text/css';
        css.href='/css/user.css';
        css.rel='stylesheet';
        document.getElementsByTagName('head')[0].appendChild(css);
});

So I have a problem when user disable javascript then thic file can't be added to page so is there any way to include css file in that page using

<noscript>..Code..</noscript>

I can't add this file directly into my head Section.

So Is it possible to add css file into my html document without using javascript?

Liam
  • 27,717
  • 28
  • 128
  • 190

5 Answers5

4

with javascript:

$("<link/>", {
   rel: "stylesheet",
   type: "text/css",
   href: "/styles/yourcss.css"
}).appendTo("head");

http://api.jquery.com/jQuery/#jQuery2

without javascript:

<noscript>
  <link rel="stylesheet" type="text/css" href="myStyles.css">
</noscript>
patel.milanb
  • 5,822
  • 15
  • 56
  • 92
1

you can try this:

<head>
  <link href="style.css" rel="stylesheet" type="text/css">
</head>
Nopesound
  • 482
  • 1
  • 13
  • 28
1

Yes it is possible to load css file without using javascipt

<head>
<link rel="stylesheet" type="text/css" href="user.css">
</head>

If you want to add css on the basis of some condition then use php if statement as shown below:

<?php if(YOUR CONDITION){ ?>
  <head>
  <link rel="stylesheet" type="text/css" href="mystyle.css">
  </head>
<?php } ?>
Anubhav
  • 1,605
  • 4
  • 18
  • 31
1
<noscript>
    <link href="style.css" rel="stylesheet" type="text/css">
</noscript>

Now you can place this code in head section and it'll be called only when javascript is disabled.

ankitjain11
  • 253
  • 2
  • 16
1

Not sure how HTML compliant this is, but you can include a link within your body tag and still have it reference the class, given that you cannot edit the head section as stated.

Doing this did work for me, referencing the 'class1' from the style.css file

<head>
</head>
<body>
<div class="class1"></div>
<link href="style.css" rel="stylesheet" type="text/css">
</body>

Edit: in HTML 4.01 it is not acceptable, however using HTML5, this is perfectly acceptable markup. If referencing a larger CSS file this may cause some elements to be without style temporarily as the head section is intended to load such documents prior to displaying content, however if this is not a possibility, then this may be a solution for you.

JaanRaadik
  • 571
  • 3
  • 11
  • 1
    This is **correct.** Stylesheets don't have to be in ``, but the sooner you add them in the page, the less likely you'll have [flashes of unstyled content](http://www.bluerobot.com/web/css/fouc.asp/). Just use `` right after your "common head section" file or use PHP in that file to add the stylesheet only on the pages that need it. – fregante Dec 27 '13 at 10:12