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

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="https://stackoverflow.com/scripts/loginChecker.js"></script>

Including CSS

<link rel="stylesheet" href="https://stackoverflow.com/css/myStyle.css" type="text/css" media="All" />

Leave a Comment