What command line tool can I use to automatically insert mtimes into urls in my css files for the purposes of breaking the cache?
/* before */
.example { background: url(example.jpg); }
/* after */
.example { background: url(example.jpg?1271298451); }
Also, I would like this tool to spit out the latest mtime as the css files mtime. (If the css file is still cached then the new urls will not get to the client.)
In searching the web, I have found very few tools that can do this. I am even considering rolling my own, but have found very little in the way of css parsers that are actively maintained. A candidate should be:
fast (I don't want to wait 30 seconds on deployment)
command line accessible (something like "cat foo.css bar.css | cssmtime > out.css")
What I've found so Far
yui compressor - initially I thought I would extend the yui compressor to do this, but found that it is implemented as a bunch of regex's and not a parser.
csstidy - last release was in 2007 and development has been suspended, but does have an option for inserting mtimes (also written in php, something I have no experience in)
cssutils - python sac implementation - seems to be actively maintained, but also seems like overkill for my needs. Also, written in python which I have experience with
csspool - ruby sac implementation - I don't know much ruby, but would like to learn
other sac implementations - There are several java implementations, and a c implementation neither of which I know much about
What's your experience?
Have you used any of these libraries? Was the experience positive? Would you recommend I go with them for my purposes?
If rolling your own is an option, you could make it a simple find/replace, no need for complex parsing here. For example if you specified which files need re-caching by adding the querystring yourself, you would do this:
.example { background: url(example.jpg?<MTIME>); }
Then your code just needs to find <MTIME> and replace. It would be about as fast as you could get and give you control over images that need re-caching and ones that don't.
Related
I have a site whose stylesheets are becoming overwhelming, and a full 50% to 90% or so is not used on certain pages. Rather than have 23 separate blocking CSS sheets, I'd like to find out which are being used on the page I'd like to target, and have those exported into one sheet.
I have seen several questions that recommend "Dust me selectors" or similar add on which will tell what selectors are and are not being used; but that's not what I want. I need to be able to export all used styles from all sheets for that particular page into one new sheet that can be used to replace the 23 others. The solution should be able to support a responsive website (media calls). The website page I'm targeting is: http://tripinary.com.
I've found: https://unused-css.com but this is a paid service and I need free;
The next closest thing I've come across is http://www.csstrashman.com/ but this does not look at stylesheets. In fact, it completely ignores them and ultimately I'm having trouble with the responsiveness of the site. Many times as well, this site just crashes.
I don't mind a programmatic solution if someone has had to do this before and can recommend a direction.
(deleted my comment to RwwL answer to make it a thorough answer)
UnCSS, whether node.js or as a grunt or gulp task, is able to list used CSS rules by an array of pages in an array of Media Queries.
uncss: https://github.com/giakki/uncss
grunt-uncss: https://github.com/addyosmani/grunt-uncss
gulp-uncss: https://github.com/ben-eb/gulp-uncss
Multipage:
You can pass files as an argument to any of the 3 plugins, like:
var files = ['my', 'array', 'of', 'HTML', 'files'],
options = { /* (…) */ };
uncss(files, options, function (error, output) {
console.log(output);
});
Avoid:
urls (Array):
array of URLs to load with Phantom (on top of the files already passed if any).
NOTE: this feature is deprecated, you can pass URLs directly as arguments.
Media Queries and responsive are taken into account:
media (Array):
By default UnCSS processes only stylesheets with media query "all", "screen", and those without one. Specify here which others to include.
You can add stylesheets, ignore some of them, add inline CSS and many other options like htmlroot
Remaining problems:
1/ Conditional classes if you use them for IE9-. They obviously won't be matched in a WebKit PhantomJS environment!
HTML:
<!--[if IE 9]><html class="ie9 lte-ie9" lang="en"><![endif]--> <!-- teh conditional comment/class -->
CSS:
.ie9 .some-class { property: value; ] /* Only matched in IE9, not WebKit PhantomJS */
Should they be added by hand or script to the html element in testing environment? (how it renders is of no importance)
Is there an option in uncss?
As long as you don't style with :not(.ie9) (weird), it should be fine.
EDIT: you can use the ignore option with a pattern to force uncss to "provide a list of selectors that should not be removed by UnCSS". Won't be tested though.
2/ Scripts that will detect resolution (viewport width) and adapt content to it by removing/adding it or adding a class on a container. They will execute in PhantomJS in desktop resolution I guess and thus won't do their job so you'll need to modify calls to PhantomJS or something like that... Or dig into options or GitHub issues of the 3 projects (I didn't)
Other tools I heard of, not tested or barely or couldn't test, no idea about the MQ part:
in grunt-uncss readme, the Coverage part
ucss from Opera (there's already an ansswer here, couldn't make it work)
Helium
CSSESS
mincss
Addy Osmani has countless presentations of 100+ slides presenting awesome tools like this one: https://speakerdeck.com/addyosmani/automating-front-end-workflow (you'll regret even more that days are made only of 24 hours and not 48 err wait 72 ^^)
How about the CSS Usage plugin for Firebug?
Steps:
Visit your page in Firefox
Click "CSS Usage" tab in Firebug
Click the Scan button
Click the bold file name
Save page of CSS selectors to disk
Here are some screen shots and walk through. Not sure about media queries or if it'll work on your site, and it'll probably not keep -webkit etc, but maybe it'll get you part of the way there.
Opera Software released a CSS crawler on Github that claims it can find unused and duplicate selectors. It might do the trick if you're comfortable with a command-line tool. https://github.com/operasoftware/ucss
You Can Check in Google Chrome by doing inspect element (F12) . The unused CSS has Line over the tags.
If you wanted, you could try to build a script that runs on a (non-production) server that goes through every css rule, removes it from the stylesheet, loads the page using something like phantomjs, and checks to see if anything changed from the last time it loaded the page. If so, then put the css rule back, if not, then leave it out and move on to the next rule. It would take a while to run, but it would work. You would also have to setup an instance of your server that does not use caching for it to run on.
Try using this tool,which is just a simple js script
https://github.com/shashwatsahai/CSSExtractor/
This tool helps in getting the CSS from a specific page listing all sources for active styles and save it to a JSON with source as key and rules as value.
It loads all the CSS from the href links and tells all the styles applied from them
You can modify the code to save all css into a .css file. Thereby combining all your css.
I started to use Bracket as my IDE. I like it...
When I edit a CSS file there is great auto-complete, but when I edit less file there is no CSS auto-complete and it would be very useful.
Is there a way to turn CSS auto-complete for less files?
For some reason there isn't any built-in support for this yet but it can easily be hacked in and works quite well.
Open C:\Program Files (x86)\Brackets Sprint 32\www\language\languages.json (or whatever path you have it installed to) and scroll down to the CSS-key. Then just add "less" to the fileExtensions-array, save it and reload Brackets.
"css": {
"name": "CSS",
"mode": "css",
"fileExtensions": ["css", "less"],
"blockComment": ["/*", "*/"]
}
For some reason this isn't enabled by default but I haven't discovered any problems with it this far. Works fine with nested declarations which I initially thought would be a problem.
Updated answer:
Autocomplete in LESS files is now enabled automatically in Brackets Sprint 36 and newer (along with the Quick Docs command). The workaround in the answer above is no longer needed.
Original answer:
There's not a way to do it yet. Brackets has a public backlog, which
includes a user story for LESS code hinting
support.
You can upvote the user story if you sign in with a (free) Trello
account.
Brackets recently added
support for CSS-like code hinting in SCSS files, but that was much
easier to do. Because the SCSS tokenizer in
CodeMirror shares code the CSS one, the two
produce very similar streams of tokens, allowing much of Brackets'
existing CSS-analysis logic to be reused. The LESS tokenizer, on the
other hand, produces different token information that would require
larger code changes to support.
But it's certainly doable -- just a matter of prioritization. That's
where backlog upvoting and/or pull requests come in :-)
ReSharper 6 considers .less files as .CSS, although they aren't.
So instead of proper syntax highlighting, it underlines nearly everything with red (syntax error).
How can I disable this "feature"?
Just found a nice trick:
// /* Disabling ReSharper ;)
// .less code goes here
// */
It's better than disabling ReSharper for a particular set of files (ReSharper -> Options -> Settings -> Edit items to skip ...), since in this case each member of your team doesn't need to repeat this.
There are a whole bunch of file types that VS tends to screw up (.haml, .less, .html, .json, etc...) and some files that you need to edit that it wont easily allow (.proj, .sln, etc...).
Best thing is to find a good text editor that you like (vim, e, textmate, notpad++, etc...) and use it along side VS.
What is the best way to handle style that that is user-customized? Just as an example of the result I'm looking for, this would suffice:
body {
color: {{ user.profile.text_color }};
}
However, serving CSS as a view seems like it would cause a significant amount of overhead in a file that is constantly requested, so this is probably not a good solution.
The user does not have access to the CSS files and we must assume that they have no web development knowledge.
However, serving CSS as a view seems like it would cause a significant amount of overhead in a file that is constantly requested, so this is probably not a good solution.
And what if you would generate that CSS once?
Default CSS is: /common/css.css
Member customize CSS, now <link /> elements points to /user-specific/123.css?ts=123123123. 123 is of course an identifier of the member, and ts parameter contains a timestamp - a date of last CSS modification
Make sure that your CSS generator sets proper HTTP headers responsible for client-side caching
User browser request a CSS file - server replies with simple 304 Not Modified header - there is no need for any script execution or contents download
When member modifies his CSS then you just update ts - once again just a single request is needed
Do the CSS dynamically via a view as normal, but use aggressive caching so that it loads quickly.
You can try django mediagenerato, actually I read this Q and I was searching for solution like you, then I found that Django-mediagenerator
I didn't tried it yet but it seams to be a solution.
I have a legacy application that I needed to implement a configuration page for to change text colors, fonts, etc.
This applications output is also replicated with a PHP web application, where the fonts, colors, etc. are configured in a style sheet.
I've not worked with CSS previously.
Is there a programatic way to modify the CSS and save it without resorting to string parsing or regex?
The application is VB6, but I could write a .net tool that would do the css manipulation if that was the only way.
You don't need to edit the existing one. You could have a new one that overrides the other -- you include this one after the other in your HTML. That's what the "Cascading" means.
It looks like someone's already done a VB.NET CSS parser which is F/OSS, so you could probably adapt it to your needs if you're comfortable with the license.
http://vbcssparser.sourceforge.net/
One hack is to create a PHP script that all output is passed through, which then replaces certain parts of CSS with configurable alternatives. If you use .htaccess you can make all output go through the script.
the best way i can think of solving this problem is creating an application that will get some values ( through the URL query ) and generate the appropriate css output based on a css templates
Check this out, it uses ASP.NET and C#.
In my work with the IE control (shadocvw.dll), it has an interesting ability to let you easily manage the CSS of a page and show the effects of modified CSS on a page in realtime. I've never dealt with the details of such implementations myself, but I recommend that as a possible solution worth looking at. Seeing as pretty much everyone is on IE 6 or later nowadays, you can skip the explanations about handling those who only have IE 5,4,3 or 2 installed.
Maybe the problem's solution, which is most simple for the programmer and a user is to edit css via html form, maybe. I suppose, to create css-file, which would be "default" or "standart" for this application, and just to read it, for example, by perl script, edit in html and to write it down. Here is just the simple example.
In css-file we have string like:
border-color: #008a77;
we have to to read this string, split it up, and send to a file, which will write it down. Get something like this in Perl:
tr/ / /s;
($vari, $value) = split(/:/, _$);
# # While you read file, you can just at the time to put this into html form
echo($vari.":<input type = text name = ".$vari." value = ".$value.">");
And here it is, you've got just simple html-form-data, you just shoul overwrite your css-file with new data like this:
...
print $vari[i].": ".$value.";\n";
...
and voila - you've got programmatical way of changing css. Ofcourse, you have to make it more universal, and more close to your particular problem.
Depending on how technically oriented your CSS editors are going to be, you could do it very simply by loading the whole thing up into a TextEdit field to let them edit it - then write it back to the file.
Parsing and creating an interface for all the possibilities of CSS would be an astronomical pain. :-)