- How to load CSS files using JavaScript?
- Example 1: Loading the CSS file on window.onload( )
- Code For loadcss1.html
- Example 1
- Code For cssfilenew.css
- Viewing The Result
- Example2: Loading the different CSS files on click of two buttons
- Code For loadcss2.html:
- Example 1
- Code For cssfile.css
- Code For cssfilenew.css
- Viewing The Result
- Use javascript to get the style of an element from an external css file
- 3 Answers 3
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Access CSS file contents via JavaScript
- 7 Answers 7
How to load CSS files using JavaScript?
Sometimes, the task is change the page themes and to use different CSS files on the same page content. In such tasks the need is to fetch a CSS and load it dynamically while selecting a theme. In this case the CSS file has to be accessed, loaded and even selected through a javascript program. Using HTML and javascript code this process of loading the CSS file is demonstrated in this article. This is shown by using two different examples. In the first example, a CSS file is selected on the windows load event. In the second example, two buttons are used to load separate CSS files on button clicks.
Example 1: Loading the CSS file on window.onload( )
Folder and Pages Design Steps −
- Step 1 − Make an html file and start writing the code. Create a CSS file and define the styles for background, p tag and h1 tag.
- Step 2 − Inside the tags in the html file, write the code which will be executed when the page is fully loaded. Use window.onload() for this.
- Step 3 − Inside the tags write the code to fetch the head tag first. Then make a link tag and set its properties.
- Step 4 − Select the css file and add it to the href of the link.
- Step 5 − Now add this created link into the head tag.
- Step 6 − Load the HTML file in a browser and check the result.
Main html file : loadcss1.html
CSS file used: cssfilenew.css
Code For loadcss1.html
Example 1
To load the CSS file using JS
Code For cssfilenew.css
Viewing The Result
For seeing the result open the html file in a browser. The styles will be included in the CSS file that is loaded using Javascript.
Example2: Loading the different CSS files on click of two buttons
Folder and Pages Design Steps −
Step 1 − Make an HTML file and start writing the code. Create two CSS files and define the different styles for the background, p tag, and h1 tag in these.
Step 2 − Inside the tags in the HTML file, make two functions, function1, and function2. Write the code for these functions which will be executed when these functions will be called.
Step 3 − Inside the tags, in both of these functions write the code to fetch the head tag first. Then make a link tag and set its properties.
Step 4 − Select the different CSS files through both functions and add these to the href of the link.
Step 5 − Add this created link to the head tag.
Step 6 − Now create two buttons and call these two functions on different button clicks.
Step 7 − Load the HTML file in a browser. The CSS file is not added initially. It will be added on the button clicks. Click both buttons and check the results.
Main HTML file: loadcss2.html
CSS files used: cssfile.css and cssfilenew.css
Code For loadcss2.html:
Example 1
To load the CSS file using JS
Code For cssfile.css
Code For cssfilenew.css
Viewing The Result
For seeing the result open the html file in a browser. The styles will be included from the CSS files that are loaded on button clicks.
3In this article, using two different examples, the ways to show how to load the CSS file dynamically using the javascript code are given. First, the method is given where a CSS file is selected when the page is loaded and then the way of using the CSS files on button click is given. For this two buttons are clicked to load different CSS files and change the style of the same page.
Use javascript to get the style of an element from an external css file
I expect the js would return «none», but it return an empty string instead. Is there any way to solve this problem?
3 Answers 3
This would work for standards compliant browsers (not IE — currentStyle/runtimeStyle).
Testing window.onload = function()
Thanks. However, our page will be used on mobile and we need to minimize the size of the page. Therefore jquery is not recommended. Is there any other way which can achieve the same result?
Might be worth mentioning that in the question. Particular mobiles? Quite a few don’t support JS at all.
@Coronatus — that would be the development version, which of course you would not deploy to a production server. The production version is only 24kb.
@Jonathan — but the minified version is effectively 155kb of code after parsing. You could minify any Java/C/PHP/Ruby file, but that won’t make it any faster to parse and evaluate.
Since display is not set directly as a style property, you won’t get that using the above code. You have to get the computed value.
You can refer this page, Get styles
var displayValue = getStyle("test", "display"); function getStyle(el,styleProp)
That function is really basic, it will have problems with CSS property names formed by two or more words (i.e. font-size , background-color , etc) and also the getComputedStyle method should be invoked from the document.defaultView object, since not all browsers have the defaultView members available on the Global object ( window ), and there are more inconsistencies, give a look to this implementation that I made: stackoverflow.com/questions/2531737/…
The CSS won’t be loaded yet. Wrap your JavaScript in an «on-ready» event.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Access CSS file contents via JavaScript
I’m not really into getting all the CSS rules via document.styleSheets, is there another way? Update: There is the ajax option of course, I appreciate the answers given. But it seems rather unnecessary to reload a file using ajax that is already loaded in the browser. So if anyone knows another way to extract the text contents of a present CSS file (NOT the CSS rules), please post!
@Diodeus it’s not a dup, as stated I’m not interested in parsing CSS values from a stylesheet, I’d like to extract the entire text contents.
7 Answers 7
With that specific example (where the CSS is on the same origin as the page), you could read the file as text via ajax :
If you want to access the information in a more structured way, document.styleSheets is an array of the style sheets associated with the document. Each style sheet has a property called cssRules (or just rules on some browsers), which is an array of the text of each rule in the style sheet. Each rule has a cssText property. So you could loop through those, e.g.:
$.each(document.styleSheets, function(sheetIndex, sheet) < console.log("Looking at styleSheet[" + sheetIndex + "]:"); $.each(sheet.cssRules || sheet.rules, function(ruleIndex, rule) < console.log("rule[" + ruleIndex + "]: " + rule.cssText); >); >);
Live example — That example has one stylesheet with two rules.
The document.styleSheet thing is nice, but not what I need. I need the EXACT text contents, not an array of rules to loop though. Perhaps I wasn’t clear on this.
@David: Then you’ll have to do the extra GET. Once the CSS text is loaded and parsed, as far as I’m aware the browser doesn’t retain the original source of it. (This is true of HTML pages as well, which is why you see «view source» do a request to get the source text.)
it would be possible load the content of css file via ajax and then create a
@David: No, when you access the innerHTML property, the browser creates an HTML string representing the current state of the DOM tree for the element (in that case, the whole document) you access it on. It’s not at all the same as the source of the page, which may be formatted differently, may have actually been different because DOM manipulation has been done since, could have omitted tags that the browser includes, may have had comments browsers don’t retain, different quoting around attributes, etc., etc.
@SlaterVictoroff — Which part? I’d be surprised at an SOP (not CORS, which is a way to loosen the SOP) violation for something on the same origin.