简体   繁体   中英

How to compress a CSS selector string, using javascript

Maybe there's a library that does this already? All I could find is online tools. The reason I want to do this in javascript is because I want to know that the string a > b, a is the same as a> b,a . If I can compress it as CSS, all versions will end up as the same string.

A better explanation of why I'm trying to do this: I wrote a jQuery plugin for myself to cache jQuery selectors (this stuff $('div') ). It works by storing a key value pair, where the key is my selector string, and the value is the DOM elements found. This is why I'd like to compare CSS selector strings, otherwise I'd be storing different keys that are essentially the same selector.

Uglify.js (https://github.com/mishoo/UglifyJS) can let you automate compression of CSS. It will strip out all unnecessary white spaces and comments. This should allow you to normalize whatever you want. You will need to look at Uglify source and attempt to extract just the needed components.

When I experimented on: http://refresh-sf.com/yui/ it seems the selector was always minified appropriately (although that was using YUI not uglifyjs). The only remaining issue is the difference between a>b,b and b,a>b. For that I would recommend first minifying then splitting by ','; then sorting the array alphabetically; and finally rejoining the split array. Once done you can use that value as the hash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM