0

How can I load/refer to an external CSS file inside an external JS file.

As shown in the below image I would like to refer/load Default.css inside Common.js

enter image description here

Thanks in advance

BB

BumbleBee
  • 10,429
  • 20
  • 78
  • 123
  • 1
    possible duplicate http://stackoverflow.com/questions/574944/how-to-load-up-css-files-using-javascript – grc Feb 01 '12 at 19:57

4 Answers4

1

You can't load a stylesheet "inside" JavaScript, you need to add the stylesheet to the DOM.

The link grc posted as a comment tells you how.

How to load up CSS files using Javascript?

Community
  • 1
  • 1
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
1

Create a new link tag in script, referencing your stylesheet.

Here's how you do it in jQuery:

$("<link/>", {
    rel: "stylesheet",
    type: "text/css",
    href: "your script here."
}).appendTo("head");
jpda
  • 738
  • 5
  • 16
  • How can I use the styles which are inside the CSS file. for ex : $('#txtExp').css(TextNormal); throws an error. TextNormal is a style inside Default.css. – BumbleBee Feb 01 '12 at 22:40
  • 1
    Once you load the CSS into the DOM, then those styles are available for assignment. What error are you getting? You may want to try `$("#txtExp").addClass("TextNormal");` – jpda Feb 01 '12 at 23:19
  • Is there an event you're doing this on? Like `$(document).ready?` Your CSS must be loaded into the DOM before this will work, i.e., you need to load your CSS before you try to do anything with it. – jpda Feb 02 '12 at 19:45
1

You can do this by creating a <link> element and append it to document.body after adding proper attributes (href, type etc) to it.

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
1

You need to try and find the absolute path of the file Default.css within the application.

From Common.js, you would be able to load Default.css using something like this:

var linkEl = document.createElement('link');
linkEl.href='/App_Themes/Default/Default.css'; // start with slash '/' for absolute path
linkEl.rel='stylesheet';
linkEl.type='text/css';
document.getElementsByTagName('head')[0].appendChild(linkEl);
Renato
  • 12,940
  • 3
  • 54
  • 85