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

1

4 Answers 4

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");
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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");
Is there an event you're doing this on? Like $(document).ready? Your CSS <em>must</em> 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.
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?

Comments

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.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.