Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best method to reduce the size of my Javascript and CSS files?

When working with large and/or many Javascript and CSS files, what's the best way to reduce the file sizes?

like image 678
nickf Avatar asked Sep 15 '08 18:09

nickf


People also ask

What can you do to reduce the size of a CSS file?

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.

Can you compress JavaScript files?

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.


3 Answers

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.

Including Javascript

<script type="text/javascript" src="/scripts/loginChecker.js"></script> 

Including CSS

<link rel="stylesheet" href="/css/myStyle.css" type="text/css" media="All" /> 
like image 75
Jim Avatar answered Sep 20 '22 16:09

Jim


Minify seems to be one of the easiest ways to shrink Javascript.

Turning on zip at the web server level can also help.

like image 20
Mark Biek Avatar answered Sep 20 '22 16:09

Mark Biek


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.

like image 30
Michael Haren Avatar answered Sep 17 '22 16:09

Michael Haren