Django module to shorten css classes in production - javascript

I have a css class:
.footer-react-btn{
color:#ddd;
}
But if I change .footer-react-btn to .a or .b, then I might save some bytes of text from being loaded.
I want it to happen in my production. I will be writing the code in an understandable manner during my development.
So, Is there any way I can do it in?
I am new here. I need an explanation step by step.

Typically, one simply maintains two files -- a-stylesheet.css and a-stylesheet.min.css. And it's usually limited to removing whitespace, not changing names. Imagine if you were using two different stylesheets and applied this same name-changing mechanism to both... You could suddenly have collisions that otherwise wouldn't exist. Plainly, just not a good idea.
At any rate, the closest thing to what you're looking for is django-compressor which combines and minifies your static JS/CSS, but it has many behaviors you may or may not want.
Frankly, it's my opinion that worrying about those few bytes is a waste of time. Simply minifying the CSS is a simpler and safer way to reduce the size of your CSS components. I wouldn't even consider more complex solutions until you really encounter scaling problems.

If you wants to see the fully expanded code in text editor and wants to send the minified css code to clients, use PHP comments.
First of all, make a file with extension php. Eg:- styles.php then add below code into it:
<?php header("Content-type: text/css"); ?>
Then add the minified code. For removing the read-hardness issue, you could add PHP comments like
You just add as many short codes as you wish but don't forget to enter the expanded information inside a PHP comment. The reason I suggested PHP comment instead css comments, is that PHP codes won't be executed by the web server. You can read both minified code and the expanded code(in comments) in the text editor but client browsers will only get the minified code loaded. So, you can decrease that data transferred....
I think that this will be helpful....

Related

How to correctly unminify js and css, and reference them in html5?

I've been helping out my friend with a project of creating a personal website and I've found this awesome jssor template for images slideshow. It comes in three versions deeply minified, without jquery and with jquery.
I've no experience with jQuery, so I decided to go with a version without jQuery, where I spent a lot of time trying to understand what is actually happening in the code. Then I have moved to deeply minified version, what is pretty neat as everything works without a single reference to css or js files.
Now, inside the deeply minified version the styles and script are written in one line. I am not going to include them in post as they are more than 30000 characters, but all the files are available within the template link mentioned above.
I've used this css unminifier - and this js unminifier - to somehow convert them into readable and understandable format. After that I've created styles and js files accordingly and pasted the unminified code there. I've added the references and paths to the files into the head of html, but for some reason nothing works.
...
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="css/text" href="style/slidestyle.css">
<script src="js/script.js"></script>
<title></title>
</head>
...
You probably ask: "Why do I need to change anything if it works without any changes?". That's true, but in that case I've no idea how it's working and hope you agree with me that it's bad.
My question and inquiry would be, how to correctly unminify css and js files and afterwords reference them in html? I assume that it is not a common practice of doing things in such a way, but I want to be able to understand how things work and change them if needed.
UPDATE: I've figured my way through and made a commit to GitHub. It's for anyone who has a similar problem or wants to understand better how slider works.
How to correctly unminify js and css
Long answer short: You don't; at least not for JS.
in CSS the minifyer I know only strip whitespace, comments and trailing ; and so; convert #FF0000 -> red and stuff like that. everything still pretty readable, so adding some line-breaks and whitespace would make the code easy on the eye.
In JS ont only unneccesary whitespace is stripped, but all local variable- and function-names are replaced by (usually) single-char names. Often used the same name for different things in different contexts. More aggressive minifyer even alter the stucture of your code to something shorter.
Almost all of our understanding of code is based on the used names and the structure of the code; so problem.
You can try to reverse-engineer something from a minified code, or sometimes you have to patch something in some other's code, but you don't un-minify code unless you really really need to, and have no alternatives.
Then I have moved to deeply minified version, what is pretty neat as everything works without a single reference to css or js files
No, It's not, it's a last-choice-solution, if anything else fails. Like in environments where you simply can't reference additional files.
Because these 30kb of CSS-String can't be cached now by the browser (like they would be if you use a separate file), and in the worst-case you add this block more than once on a page, so it's just bloating your HTML and slowing down your page.
You probably ask: "Why do I need to change anything if it works without any cahnges?". That's true, but in that case I've no idea how it's working and hope you agree with me that it's bad.
If you want to understand how it's working, take a look at the jQuery-version. Since jQuery is an external library, the minifier can't strip the method-names utilized. 2nd the code is more dense, since you don't have to read through code that manages an animation, you just read a call to animate these properties on these object to these values, and so on. This gives you a better understanding of what's going on in this code without the implementation-details.

Loading CSS (& possibly JS) with PHP

If you have a lot of files, would there be any benefit to doing something like this in the header:
<style type="text/css">
<?php
include("css/myCss1.css");
include("css/myCss2.css");
include("css/myCss3.css");
include("css/myCss4.css");
include("css/myCss5.css");
?>
</style>
That way server returns one file instead of several. You can also load the content from js in between script tags.
Please don't flame, just explain why this would or would not make sense in a situation where you need to have a lot of individual files and you want to consolidate instead of having the main file make calls for those files individually.
I've tried and they seem to work... but what are the repercussions on the server or benefits of speed (if any).
Just curious... Thank you very much.
UPDATE: Thank you for all replies... Would another solution (that would deal with the cache issue) be to have 1 external php file that load all the other css into it - sort of combining all into 1?? Does that make sense?
You should use an external stylesheet, so it can be cached separately because in most cases PHP is used for dynamic data retrieved from databases and you might not want to cache all the data. If you are not using PHP for anything else than merging CSS, you should definitely use LESS # http://www.lesscss.org, as it is a CSS preprocessing language that has many features that make developing CSS easier which includes merging css files together. You could also try SASS # http://sass-lang.com/ which is similar. This way you reduce the number of HTTP requests, the server doesn't have to keep running PHP code unnecessarily, and don't do as many reads from disk.
Of course that would work, but since the size of HTML output content remains the same and same number of KiloBytes are sent to the client, there is no real benefit here.
And there could be many downsides, first up it would be hard to debug which file to update when you have to update any css class. You'll have to find that manually.
But one major point against this would be that PHP includes are not meant for CSS includes. Although that might appear to work for you, a source code include is for source code. Its bad programming practice and also it requires PHP to parse all those CSS files unnecessarily. This unwarranted parsing of your CSS files will counter the benefits you will obtain by that. Rather you can simply merge all those CSS files together into one.
In addition to Hanky Panky's answer, when including CSS files with HTML code, browsers may cache the CSS file locally, making less data be transferred between the server and the client.
When including the CSS with PHP like in your question, there can be no such local caching of the CSS.
Edit: Using one single PHP for all the CSS could in theory only work if you include the PHP-CSS as a stylesheet using HTML-code. Writing <style type="text/css"> in either the PHP-CSS file or using include inside such statement in your main file would not help. However, either way it is not something that I would recommend. PHP is not for including many CSS-files into one.

Is there a danger to creating a js file that simply uses document.write() to bundle js and css files?

I am building a front-end UI framework for developers in my firm to use to build internal web apps. It consists of customized Bootstrap, jQuery, other open-source libraries, internal modules and stylesheets. The user environment is entirely IE9 and my server is .NET 3.5. I am hosting the shared files. Dev teams in the firm will place the links in their project pages and apply the framework to their pages.
I want to offer them the simplest method of implementing this which would be one line of code to paste that builds the library for them. Cutting and pasting 30 lines of code is stale the moment Ctrl + V is pressed, it leaves me no control and is simply inelegant.
Failed Experiments
I tried using Head.js and LazyLoad both of which use best practices for inserting scripts. But each of them has caused either content to display before styled or conditions where methods are called before scripts load. I am giving up on this approach.
It's too volatile.
A simple document.write() solution
Over the weekend, I thought: Why don't I just make a js file named "framework,js", add the script and link files in order with a stack of document.write() lines. Tell developers to put it in the head and that's it. Heck I could add the necessary metatags for IE9 and mobile too for that matter. It's so nasty and simple... but it just might work!
The user base is on an internal network and of limited size. Bandwidth is not a problem. I'll test performance before I choose this. I can direct the developer teams on where to place the link.
Knowing this and providing it actually works, is there any reason why I shouldn't do this?
My only other option to explore is bundling on the server. I am hoping not to have to resort to this since I don't own the server myself and I am not a .NET developer.
Your proposed approach is an excellent one for your situation. It has several advantages over the more sophisticated solutions, including utter simplicity, completely predictable order of execution, and full compatibility with scripts that may not lend themselves to asynchronous loading. I have used it many times in production applications, as have many other developers.
Of course the other solutions have their advantages too, but for what you're doing there is nothing wrong with good old document.write().
It sounds like you have a number of scripts and stylesheets and are probably loading them from a common directory (or a common root directory). To reduce repetition in your framework.js file, you might want to define two functions, one to write a <link> tag for CSS and another to write a <script> tag for JavaScript. So a skeleton framework.js file might look something like this:
(function() {
var scriptBase = 'js/';
var styleBase = 'css/';
function writeStyle( name ) {
document.write(
'<link rel="stylesheet" href="', styleBase, name, '">',
'</link>'
);
}
function writeScript( name ) {
document.write(
'<script src="', scriptBase, name, '">',
'</script>'
);
}
writeStyle( 'one.css' );
writeStyle( 'two.css' );
writeScript( 'one.js' );
writeScript( 'two.js' );
})();
Note that you don't have to do any special escaping of the </script> text as you may see in code that uses document.write(). That's only necessary when you're putting this code directly inside a <script> tag within the HTML file. The purpose of that escaping is to prevent the enclosing <script> tag from being closed by the </script> text inside the document.write() call. Since your code is in an external .js file this is not an issue: the presence of the </script> text inside this file won't terminate the .js file.
Another point to keep in mind is that all of the document.write() calls you make inside a .js file are inserted into the document after the .js file that writes them. So don't expect to be able to do a document.write() inside framework.js and then have other code inside framework.js that depends on the .js file you just wrote. All of those .js files (and .css) are loaded after framework.js, not interleaved with it.
One more consideration, of course, is load time. Your page could load faster if you combine and minify your CSS and JS files. But if these are internal web apps, page load time may be the least of your worries: reliability and maintainability may be more important. And in any case you can always use the document.write() solution to get up and running right now, and later optimize this only in the unlikely event that you need to.

What are the advatanges of less?

http://lesscss.org/
Yeah the language syntax looks cool, but are there any significant advantages?
Because from what I see there you actually write more CSS, and since the less stylesheet gets compiled by javascript you get a un-styled site for a few seconds...
That is if you use lesscss for client side sheet generation.
You can also use lesscss on the server side or even compile your sheets before hand.
For example, if you are using node.js you can generate your sheets on the server.
Additionally, if you want, you can use it as a way to write more manageable templates and then "compile" your sheets to generate a formed style sheet for when you are reading for production.
I think it makes perferct sense, because it means that while you are in development, you can change a collection of colors in a single hex color change. When you are ready to deploy, you can compile before hand and then distribute that style sheet with your project.
Think about manageability and using the command line compiler.
Command Line
http://lesscss.org/
Less comes with a binary, which lets you invoke the compiler from the
command-line, as such:
$ lessc styles.less
This will output the compiled CSS to stdout, you may then redirect it to a file of your choice:
$ lessc styles.less > styles.css
To output minified CSS, simply pass the -x option.
Why would you write more CSS using LESS? In the contrary, you write less. And the code that you write is way more verbose than normal css. You can create groups better, use inheritance... You just have a way better overview over your styling than you do with CSS.
My CSS-file for a project currently has over 800 lines... in LESS, it's just around 150.
And to the javascript-compiling: I generally use an offline compiler and upload just the compiled CSS, so I don't have to fuss with the JS client.
You can use a precompiler (ruby's got a cool one, got it running under win).
Try writing a site in less and you'll never want to get back to normal css again :) my own experience...
There is actually a LESS PHP compiler, which I use all the time. I think the best way to work out why it's better than CSS is to use it yourself, but I'll summarise some things:
If you have theme colours used all over the place, for example, and want to change them, it's very easy with LESS's variable system.
You actually write less markup than vanilla CSS, due to not having to retype long selector strings.
If you want to, say, use cross-browser rounded corners, the mixins reduce repetition to almost nothing; all you do is create a class with style definitions in it, and then simply "mix it in". Essentially it's a re-usable function. If you need to change something specific to all rounded corners elements, you just change the single function.
Yeah the language syntax looks cool Personally I think this is rather dismissive and ignorant; if you have a look around the LESS examples, you will see it is miles ahead of normal CSS in terms of usability and speed of development.
There are more reasons, but these should be enough to get you started.

Can I make a custom colour definitions that I can share between CSS, JS and HTML?

I have a blue-ish colour that I want to use in many places in my app and at the moment I am copying and pasting it between styles in my CSS. Is there a way of defining a constant like the standard colours, 'blue', 'red' etc. that I could share between my CSS, my HTML and my JS?
I'd like to be able to say (somewhere, preferably CSS)
myblue = #33CC99
in CSS say...
background-color:myblue;
in HTML say...
<td color="myblue"/>
and in JavaScript
tag.style.backgroundColor = myblue;
I'm guessing this is impossible and google turned nothing up, so has anyone got any ideas? I doubt I am the only person to come across this.
A very promising product that "compiles" higher-level expressions like variables into CSS is LESS. It needs Ruby. I haven't used it yet but it's definitely worth a look.
A more primitive way to do this would be using a server-side scripting language like PHP.
You would define constants in PHP like so:
define ("MYBLUE", "#33CC99");
and then outputting the value where needed using <?=MYBLUE;?>
Big downside: To do this in external css and js files, you would obviously have to have them parsed by the PHP interpreter, which is not good performance wise if you have a lot of visitors. For a low-traffic site, it probably doesn't matter.
Yes, this is impossible. You could, however, write your own CSS preprocessor (or use one of the existing ones out there), for instance with PHP. The big downside is that you would have to output the colorcode on your whole site with PHP and your scripts would look like
tag.style.backgroundColor = <? echo $myblue; ?>
and likewise in CSS
.someClass {
background-color: <? echo $myblue ?>
}
or something similar. And that isn't really nice either. Of course you could use any server sided script language of your choice. As far as I can judge, this is the only possibility to use a color-constant throughout a whole website.
You could have a look at some processors:
http://cssp.codeplex.com/
http://www.shauninman.com/archive/2007/06/27/css_server_side_pre_processor
http://icant.co.uk/articles/cssconstants/
You may look at HAML+SASS. Though you cannot define variables for all three languages at once, these two can make writing HTML+CSS much easier.
How I would approach this is to make a class in my CSS.
.color_class {color: #33CC99;}
Then call it in my HTML
<td class="color_class" />
You can assign multiple classes to an HTML element.
In the JS, just name the class
document.getElementById('id').className = 'color_class';
Of course you can play with how you want to select your element. A JS library probably has even easier methods for assigning CSS classes.
To achieve this with out using any dynamic CSS (e.g. serving a PHP file with content-type text/css), your best bet is to separate out the places where you define the 'theme'.
<script type="text/javascript">
var theme = '#003366';
</script>
Then you can use a JavaScript file to write out styles based on the themes.
However, if you are able to use a CSS pre-processor, go with that. You'll have much more flexibility and the code will be easier to maintain. I almost always use a PHP or JSP page for CSS.
As other users have noted you can't do this in straight HTML, JS or CSS unless you pass all HTML, JS and CSS content via a CGI/PHP/ASP script - which isn't actually a bad approach as it's easy to maintain.
If you use a query string in the reference to included CSS / JS files - e.g. '/css/stylesheet.php?timestamp=2010-01-01+00:00:00', then almost all clients will aggressively cache your CSS/JS files, negating any impact on load parsing them in a scripting language may have (though unless the site is likely to be particularly busy I wouldn't be too connected about that).
If you are using Apache (which is likely), an alternative approach would be do use something like mod_set to re-write all HTML, JS and CSS files on the fly for you. This may be more difficult to support if you are not familiar with configuring Apache (or are using another web server).
With regard to tag naming:
With either approach I strong suggest using a clear tagging system to denote your dynamic variables (e.g. %MyBlue%) and to consider having variables names be representative (e.g. %HeadingBackgroundColor%, %FontColor%, even if both are set to %MyBlue%), as that can prevent things getting hairy later on (when you discover that changing one value has intended consequences).
Using more representative names may seem unnecessarily verbose at first glance, but it causes problems in many cases because colours end up clash in unintended ways when they are significantly different from the original scheme (this is true of a lot of mainstream software which is skinnable - because the author made the assumption that %value1% and %value2% would always go together and so would %value1% and %value3% - meaning in effect the options for themeing are severely limited by an unintended dependancy).
I do this at build time by running my CSS files through Freemarker.
I am not sure of your end goal. If it is to allow selection of one of several themes for a web page, you could simply have multiple CSS files, and a cookie/session variable/database store of the user's prefered style sheet. Then you could just do
<link rel=<? echo stylepref; ?> type='text/css'>
or something along those lines
If you want to be able to completely customize the site, then one of the above answers would be needed.
There's no concept of 'variables' in CSS, but I'd strongly recommend not doing what you're doing. there's no good reason that you can't define all your style information in your CSS sheet as CSS classes. If you do that, and then just apply said classes in html and javascript, that's one major load off in terms of copying and pasting.
Second, remember that you can define more than one CSS class for an element, e.g.
<div class='blue-text white-background'>my content</div>
You can then define those independantly in CSS, a la:
.blue-text { color : Blue; }
.white-background { background-color: white;}
and you can even create rules that only take effect when both are applyed:
.blue-text.white-background { color : AliceBlue; }
If you want to have the color choices dynamically generated, the only real way to do that is as others have suggested, which is either preprocess your files before deployment, or have the CSS dynamically generated and served by your language of choice.
In pure client side CSS grouping selectors allows you to put the same color on many different elements:
p, .red, #sub, div a:link { color: #f00; }

Categories