I'm working on a non-web platform with no HTML or CSS layer, just a pure JavaScript implementation.
I would like to load a CSS file as a text string using AJAX, parse the CSS into a JS objects or JSON, and then use utility library to interpret what styles should be applied to an element in the DOM tree.
How would I do that?
Custom selector property/values can be used in CSS JSON as a mechanism to extend CSS. CSS text pre-processing is possible through the mapping of a specfied property to a conditionally executed parsing routine.
JSON.parse() A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON.parse() , and the data becomes a JavaScript object.
The JSON file will be parsed for you automatically and you can start using it in your project: const jokes = require('./jokes. json'); console.
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
I think you're looking for a "JavaScript CSS parser".
Have you looked at either of these?
http://www.glazman.org/JSCSSP/
or
http://bililite.com/blog/2009/01/16/jquery-css-parser/
The first one looks like a good fit, but if you like jQuery then maybe you'd prefer the second one.
HTH
I looked at both the links @amir75 suggested. The first looked best, but the code was far too long for what I was doing. I decided to put a lightweight script together. It doesn't use jQuery, but you can if you want to load a CSS file using .get()
etc. Take a look at the example.html and the js console output to get a look at the structure. You can choose to keep the order of the elements if you're using comments in the CSS, or otherwise it will still keep the order of the elements but not those of the comments while using a simpler JSON structure.
https://github.com/aramkocharyan/CSSJSON
Usage:
// To JSON, ignoring order of comments etc
var json = CSSJSON.toJSON(cssString);
// To JSON, keeping order of comments etc
var json = CSSJSON.toJSON(cssString, true);
// To CSS
var css = CSSJSON.toCSS(jsonObject);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With