Question

I have minified my javascript and my css.

Now, Which is better?

<script type="text/javascript">
<?
  $r = file_get_contents('min.js');
  if($r) echo $r;
?>
</script>

OR

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

Same question for CSS.

If the answer is 'sometimes because browsers fetch files simultaneously?' Which browsers, and what are examples of the times in either scenario.

Was it helpful?

Solution

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

...is better, as the user's browser can cache the file.

Adding a parameter to the src such as the file's last modified timestamp is even better, as the user's browser will cache the file but will always retrieve the most up to date version when the file is modified.

<script type="text/javascript" src="min.js?version=20081007134916"></script>

OTHER TIPS

It's better the most times to include javascript and css files because that way the browser is able to cache the javascript/css file. That way the file is only loaded once by the browser even if you include the file in several other pages.

But this is only true if you set an appropriate expires and/or cache-control header for javascript and css files via php or Apache mod_expires.

Based on the recommondation by the Yahoo Exceptional Performance there is only one exception:

The only exception where inlining is preferable is with home pages, such as Yahoo!'s front page and My Yahoo!. Home pages that have few (perhaps only one) page view per session may find that inlining JavaScript and CSS results in faster end-user response times.

I higly suggest you try out the Addon "YSlow for Firebug". It answers alot of questions about caching and browser/client -performance.

See also:

Apache mod_expires

Best Practices for Speeding Up Your Web Site

YSlow

Remember that the browser can download AT MOST two files in parallel from the same domain (that's the default on the modern browsers - i'm certain about IE6 and IE7, not sure about others). This means that if your page references 20 tiny javascript files, many will get downloaded sequentially.

To add to what was already said: remember that if you combine/minify your javascript files, it's better to merge them all into one - the compression will work better. Additionally, even if you don't minify your files, remember to turn on GZIP in your web server config; then, if you combine all your JS files into one and include that file as , the GZIP compression will work best (because compressing two JS files together produces better results than compressing each separately).

If you're looking for a good JS minification utility, try JS Packer (http://dean.edwards.name/packer/)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top