Alex Rivera | Logout

Multiple javascript/css files: best practices?

Asked 2009-01-29T05:56:37.530
57

I have about 7 Javascript files now (thanks to various jQuery plugins) and 4-5 CSS files. I'm curious as to what's the best practice for dealing with these including where in the document they should be loaded? YSlow tells me that Javascript files should be--where possible--included at the end. The end of the body? It mentions that the delimeter seems to be whether they write content. All my Javascript files are functions and jQuery code (all done when ready()) so that should be OK.

So should I include one CSS and one Javascript file and have those include the rest? Should I concatenate all my files into one? Should I put Javascript my tags at the very end of my document?

Edit: FWIW yes this is PHP.

Edit
Report

2 Answers

38

I would suggest using PHP Minify, which lets you create a single HTTP request for a group of JS or CSS files. Minify also handles GZipping, Compression, and HTTP Headers for client side caching.

Edit: Minify will also allow you to setup the request so that for different pages you can include different files. For example a core set of JS files along with custom JS code on certain pages or just the core JS files on other pages.

While in development include all the files as you normally would and then when you get closer to switching to production run minify and join all the CSS and JS files into a single HTTP request. It's really easy to setup and get working with.

Also yes, CSS files should be set in the head, and JS files served at the bottom, since JS files can write to your page and can cause massive time-out issues.

Here's how you should include your JS files:

</div> <!-- Closing Footer Div -->
<script type="application/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"></script>
</body>
</html>

Edit: You can also use Cuzillion to see how your page should be set up.

answered 2009-01-29T06:42:40.977
0

The idea of minifying and combining the files is great.

I do something similar on my sites but to ease development I suggest some code which looks like this:

if (evironment == production) {
  echo "<style>@import(/Styles/Combined.css);</style>"
} else {
  echo "<style>@import(/Styles/File1.css);</style>"
  echo "<style>@import(/Styles/File2.css);</style>"
}

This should let you keep your files separate during dev for easy management and use the combined file during deployment for quicker page loads. This assumes you have the ability to combine the files and change variables as part of your deploy process.

Definitely look into including your js at the bottom and the css at the top as per YUI recommendations as keeping the JS low has a tangible affect on the appearance of the rest of the page and feels much faster.

answered 2009-01-29T07:31:28.740

Your Answer