When working with large and/or many Javascript and CSS files, what's the best way to reduce the file sizes?
You can reduce the file size of your CSS files by removing unnecessary white-spaces, line breaks, indentations, comments, semicolons, quotes and by combining rules when possible. I personally use an online tool like https://compresscss.net/ to make things easier.
Javascript code can be compressed in one or more of the following ways: By removing white spaces and indentation. By shortening variable names to single characters. By removing new line characters.
In addition to using server side compression, using intelligent coding is the best way to keep bandwidth costs low. You can always use tools like Dean Edward's Javascript Packer, but for CSS, take the time to learn CSS Shorthand. E.g. use:
background: #fff url(image.gif) no-repeat top left;
...instead of:
background-color: #fff; background-image: url(image.gif); background-repeat: no-repeat; background-position: top left;
Also, use the cascading nature of CSS. For example, if you know that your site will use one font-family, define that for all elements that are in the body tag like this:
body{font-family:arial;}
One other thing that can help is including your CSS and JavaScript as files instead of inline or at the head of each page. That way your server only has to serve them once to the browser after that browser will go from cache.
<script type="text/javascript" src="/scripts/loginChecker.js"></script>
<link rel="stylesheet" href="/css/myStyle.css" type="text/css" media="All" />
Minify seems to be one of the easiest ways to shrink Javascript.
Turning on zip at the web server level can also help.
Rather than tweaking your files directly, I would recommend compressing them. Most clients support it.
I think you'll find that this is easier and just as effective.
More details from Jeff's adventures with it.
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