The Storyteller

Performance tips for web applications

August 1, 2007 · 49 Comments

I have recently came by the article “High performance websites” in yahoo developer network. This article pointed 13 key points to speed up your application. These are

1. Make Fewer HTTP Requests
2. Use a Content Delivery Network
3. Add an Expires Header
4. Gzip Components
5. Put CSS at the Top
6. Move Scripts to the Bottom
7. Avoid CSS Expressions
8. Make JavaScript and CSS External
9. Reduce DNS Lookups
10. Minify JavaScript
11. Avoid Redirects
12. Remove Duplicate Scripts
13. Configure ETags

I was trying to improve performance for a web application recently keeping them in mind. Let me describe how to do some of them technically.

Making fewer HTTP requests:
Each time file loads from your web server, it generates an http request. So you can reduce number of http requests by caching some contents which are almost static or changes very rarely. if these contents are loaded from browser cache, there will be no request for them over HTTP. You can use apache’s mod_expire module to cache specific tyyou (image, swf etc) of contents in your site. The following line in httpd.conf loads mod_expire successfully.

LoadModule expires_module modules/mod_expires.so

After that, write the following lines in .htaccess to cache all the image, swf and javascripts for one month from the current date, with the help of mod_expire

ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/png A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType application/x-javascript A2592000
ExpiresByType application/x-Shockwave-Flash A2592000

If you are confused by the letter “A” with number of seconds associated with it, it actually means “Access time”

For reducing number of HTTP requests, you can also merge all your css files and javascript files into one css and js file.

Use a content delivery network
Yeah, that works really cool. You can serve your static contents more effectively from popular content delivery network (CDN) like akamai or Amazon S3. The benefit of using popular CDNs is that these CDNs are scaled and distributed and really knows how to serve your content faster than ever.

Add an Expiry Header
Expiry tags helps your browser to understand when to invalidate cache for a cached content. So you can ask how to add expiry header to your content. You can do it by injecting HTTP headers while delivering it from your server to end user’s machine i.e browser. Apache’s mod_expire module does the same thing, by MIME type of contents. But it doesn’t help to cache a single file or multiple files. So if you want to cache a specific file, you can do it using following PHP code.

<?php
header("Expires: ".gmdate("D, d M Y H:i:s", time()+600)." GMT");
header("Cache-Control: max-age=600");
?>

This will set the expiry time 600 seconds from the time of content delivered.

Gzip components
While delivering any data from web server to browser, you can apply gzip compression over it. These gzipped data are decompressed when received by brwsers and treated as regular data. Almost all of the modern browsers supports gzip compression. To compress your content, you can do it either automatically using Apache’s mod_deflate or manually via your code. If you like to do it using mod_deflate, then you have to enable mod_deflate first and then modify your .htaccess file to make use of that. The following line in httpd.conf enables mod_deflate with apache

LoadModule deflate_module modules/mod_deflate.so

Now if you want to make use of mod_deflate and compress your content on the fly while delivering, you can add the following line in your .htaccess file.

AddOutputFilterByType DEFLATE text/html text/plain text/xml application/x-javascript

Or you can write PHP code for delivering gzipped contents. The following piece of code delivers any javascript file as a gzipped one.

<?php
//gzipjs.php
ob_start("ob_gzhandler");
header("Content-type: text/javascript; charset: UTF-8");
header("Cache-Control: must-revalidate");
$offset = 60 * 60 * 24 * 3;
$ExpStr = "Expires: " .
gmdate("D, d M Y H:i:s",
time() + $offset) . " GMT";
header($ExpStr);
include(urldecode($_GET['js']));
?>

To deliver a javascript file (say prototype.js) using gzipjs.php you can load your scripts like this

<script type=”text/javascript” src=”gzipjs.php?js=prototype.js” ></script>

But hey, don’t just include any file passed to it (as i did it here in gzipjs.php). I wrote the code quickly to demonstrate the process. In practice you must (M.U.S.T) sanitize the supplied argument before including. Otherwise it could be a very dangerous security breach.

Minify Javascripts
Minifying means compressing javascripts by removing unnecessary white space, comments and others. You can make use of customized rhino engine which is used by dojo’s shrinksafe. Rhino is a nifty tool for doing these things.

So, how to do it? Download custom_rhino from dojo’s shriksafe page. After that compress your javascripts using following command.

java -jar custom_rhino.jar -c infile.js > outfile.js

That means you must have JRE installed in your machine to execute the command shown above (rhino is developed using java). Now if you have number of script files and you want to compress them all at once, without applying his command for each of them, you can make a nifty batch file to do it for you. Here is the code. It will compress each script files into script.js.packed file.

for /F %%F in ('dir /b *.js') do java -jar custom_rhino.jar -c %%F > %%F.packed 2>&1

Place custom_rhino.jar file and all your script files in same directory and run it. All your scripts will be packed.

I hope these tips will really boost up performance of your web application. This is just a basic article and I didnt go details of these tips. There are also other ways (like javascript on demand) which will also help increasing the performance.

Don’t forget to check other options from the original article at yahoo developer network.

Reference
1. http://betterexplained.com/articles/speed-up-your-javascript-load-time/
2. http://www.fiftyfoureleven.com/weblog/web-development/css/the-definitive-css-gzip-method
3. http://httpd.apache.org/docs/2.0/mod/mod_expires.html
4. http://httpd.apache.org/docs/2.0/mod/mod_deflate.html
5. http://developer.yahoo.com/performance/rules.html

Categories: Amazon ECS · Apache · CSS · Javascript · PHP · performance

49 responses so far ↓

  • Omi Azad // August 1, 2007 at 10:35 pm | Reply

    WOW

    But I think we have some gzip compression options in-built in Apache server, isn’t it?

  • raju // August 1, 2007 at 10:39 pm | Reply

    a really great article. some points really helped me. thanks a lot man :)

  • Md. Rafiqul Islam // August 1, 2007 at 10:39 pm | Reply

    coooool article….

    definitely this will help for performance improvement..

  • hasin // August 1, 2007 at 10:40 pm | Reply

    @omi – nope!

  • Ehab's Playground // August 1, 2007 at 10:49 pm | Reply

    Performance tips for web applications

    Bangladesh based PHP developer Hasin Hyder writes about improving performance for your web based applications.
    <div class=quote>
    1. Make Fewer HTTP Requests
    2. Use a Content Delivery Network
    3. Add an Expires Header
    4. Gzip Components
    5. Put CSS …

  • Ehab // August 1, 2007 at 10:54 pm | Reply

    Regarding gzip, all you have to do it enable it ? or download the mod n then enable it : ( ?

  • Andrew Magruder // August 1, 2007 at 11:08 pm | Reply

    You’ll want to be careful with some of those suggestions. For example, the initial release of WinXP doesn’t work with compressed JS and/or CSS in some circumstances. For our site, that’s 15-20% of the traffic or about as much as FireFox, for us, as a relative example.

    You’ll want to pull & check user agent strings in your PHP code (look for the SV1 which indicates at least WinXP SP2) or configure mod_deflate (what we did) appropriately.

    Andrew

  • hasin // August 1, 2007 at 11:11 pm | Reply

    @andrew

    Thanks, yeah I have seen the examples at mod_deflate page. As it is for basic idea, I didn’t go that details. :)

    and hey, Thanks for the WinXP tips. Didnt know that!

  • Ashraf // August 1, 2007 at 11:17 pm | Reply

    really a very important article for web developers. Every web developer should know these things. Thanks hasin vai. :)

  • sapphirecat // August 1, 2007 at 11:32 pm | Reply

    For gzipjs security, you really want readfile() instead. Unless, for some reason, your JavaScripts are preprocessed by PHP.

  • Mrasnika’s Lair » Eх, малко време за четене на блогове // August 2, 2007 at 12:33 am | Reply

    [...] Performance tips for web applications [...]

  • buggedcom // August 2, 2007 at 2:23 am | Reply

    Interesting reading. But screw using java to remove the white space from javascript. This isn’t 100% perfect as some javascript regex and some instances of urls within strings get comfused with javascript comments and are stripped. However these instances can be fixed by minor javascript workarounds and are few and far between.

  • buggedcom // August 2, 2007 at 2:24 am | Reply

    /**
    * Compresses code (ie javascript and css) whitespace.
    *
    * @param string $code
    * @return string
    */
    function compressCode($code)
    {
    // Remove multiline comment
    $mlcomment = ‘/\/\*(?!-)[\x00-\xff]*?\*\//’;
    $code = preg_replace($mlcomment,”",$code);
    // Remove single line comment
    $slcomment = ‘/[^:]\/\/.*/’;
    $code = preg_replace($slcomment,”",$code);
    // Remove extra spaces
    $extra_space = ‘/\s+/’;
    $code = preg_replace($extra_space,” “,$code);
    // Remove spaces that can be removed
    $removable_space = ‘/\s?([\{\};\=\(\)\\\/\+\*-])\s?/’;
    $code = preg_replace(’/\s?([\{\};\=\(\)\/\+\*-])\s?/’,”\\1″,$code);
    return $code;
    }

  • TRIVUz // August 2, 2007 at 6:45 am | Reply

    great hasin bhai. i like your new outlook too :D

  • Ahsan // August 2, 2007 at 9:43 am | Reply

    Thanks for sharing.

  • hasin // August 2, 2007 at 11:23 am | Reply

    @buggedcom

    well, there are many online compressor too. but afaik, rhino is mozilla’s builtin javascript parser and team dojo modified it to do the job effectively.

    thanks for your snippet.

  • saikat // August 2, 2007 at 11:31 am | Reply

    Thanks for posting this tip vaiya. Looks straight forward. I am sure the concepts will help any web developer to build sites for high performance.

  • Tahmid Munaz // August 2, 2007 at 12:01 pm | Reply

    Hasin Rocks! (Y)
    Nice guideline for Performance improvement :) Great thing to share!

  • Samiha Esha // August 2, 2007 at 12:06 pm | Reply

    Great :) Superb Hasin bhaia :)

  • ipshita // August 2, 2007 at 12:27 pm | Reply

    I have found ‘minify Javascript’ point most interesting and didn’t know about Rhino.. so that will defiantly help to make our site much efficient. thanks, nice post!

  • Shams // August 2, 2007 at 1:33 pm | Reply

    Really great articles and cool examples.

    I would really like you to expand on the
    6. Move Scripts to the Bottom topic and how it could be done for js with variables and inline htmls. Thanx in advance.

    One of my first reads on javascript taught me to avoid ‘onload’ in body and replace the function call with script tags just before the body tag closes. I guess this is a very good example for ‘Move Scripts to the Bottom’

  • Imran M Yousuf // August 2, 2007 at 2:29 pm | Reply

    I actually view all the tips as quite beneficial. Especially the GZip compression one.

    Thanks, hope to receive more tips soon :)

  • Paul Stamatiou // August 2, 2007 at 2:44 pm | Reply

    Is S3 a true CDN? It doesn’t have an SLA and when I ping it from different parts of the country, the responses seem to come from the same datacenter rather then datacenters closer to where the request was made from.

  • Bala // August 2, 2007 at 8:22 pm | Reply

    Hasin,

    Nice article and i’m sure it will helps for lot of developers….

    Cool buddy :)

  • Ehsan // August 2, 2007 at 10:17 pm | Reply

    Thanks for sharing. Nice guidelines for developers.

  • test 08/02/2007 « Strange Kite // August 2, 2007 at 11:44 pm | Reply

    [...] test 08/02/2007 Performance tips for web applications « The Storyteller [...]

  • evølutiøn-515.net » Blog Archive » Web page loading performance tipps // August 3, 2007 at 12:17 am | Reply

    [...] Storyteller has made some suggestions on his his blog to increase web site performance that are also worth a look  if you already compress your [...]

  • nhm tanveer hossain khan (hasan) // August 3, 2007 at 12:56 am | Reply

    omg, i am so later reader
    anyway bro, the write up was important because now these days people are developing many web applications for community.

    so after getting a lot of user base the service turns in to the slowest one. the performance concerns are really encouraging. obviously premature performance tuning always cost a lot of bucks ;)

    i really need to point again about “expire” tip, the expire is one of powerful tools for ajax or heavy javascript, css, image driven site.

    thanks for reminding the right position for scripting or DOM related functionalities. it really scale for browser.

    best wishes;

  • Unatine :: blog : links for 2007-08-02 // August 3, 2007 at 6:31 am | Reply

    [...] Performance tips for web applications [...]

  • links for 2007-08-03 « Simply… A User // August 3, 2007 at 6:42 am | Reply

    [...] Performance tips for web applications « The Storyteller (tags: application applications help optimisation optimization performance programming php apache web tips **) [...]

  • links for 2007-08-03 at DeStructUred Blog // August 3, 2007 at 8:19 am | Reply

    [...] Performance tips for web applications « The Storyteller (tags: Performance Web Tips) [...]

  • Fatih Hayrioğlu’nun not defteri » 03 Ağustos 2007 Web’den Seçme Haberler // August 3, 2007 at 1:04 pm | Reply

    [...] Web sayfalarınızın performansını arttırmanın yolunu anlatan İngilizce bir makale. Link [...]

  • My daily readings 08/03/2007 « Strange Kite // August 3, 2007 at 5:37 pm | Reply

    [...] My daily readings 08/03/2007 Performance tips for web applications « The Storyteller [...]

  • Top Posts « WordPress.com // August 4, 2007 at 6:01 am | Reply

    [...] Performance tips for web applications I have recently came by the article “High performance websites” in yahoo developer network. This article pointed 13 […] [...]

  • Junal // August 5, 2007 at 1:14 am | Reply

    thx for explaining all 13 tips. it helped me to understand them better.

  • Famous last words of Marius » RSS feed update - 6 August 2007 // August 5, 2007 at 2:50 pm | Reply

    [...] development and PHP – Performance tips for web applications WSO2 Web Services Framework (WSF)/PHP v1.0.0 Released Good links related to Zend [...]

  • Dicas de performance para sites web « Chaos Mind getting into order // August 6, 2007 at 7:34 pm | Reply

    [...] Performance tips for web applications – [The Storyteller] [...]

  • S.A.M Harun // August 7, 2007 at 3:03 pm | Reply

    Thanks Hasin vai, Its very helpful for the web programmers.

  • TansComputer // August 9, 2007 at 5:45 pm | Reply

    Thx alot.. nice Refrences
    i’ll try it at joomla

  • ryo // August 26, 2007 at 9:57 pm | Reply

    Great article, i have try it and it really improve my performance. Thanks for it.

  • sam // September 2, 2007 at 1:16 pm | Reply

    Salam Bhai Kamon achen?
    ekta doubt ache hasin bhai,

    I have install the wordpress in the root of my website , which works fine.

    But now I want to create a page in a folder which is located outside of wordpress folder( in the root), name ” portfolio” , so how can i get the wordpress theme template applied to those pages in the portfolio folder. ?? with all the header, footer ,background and sidebar???

    Could you help???

  • Saidur Rahman // September 12, 2007 at 7:23 pm | Reply

    Hasin Bhai,

    From your articles, I want to try to follow in my Codeigniter based Application. To apply this things I have some question.

    Gzip components:

    To apply gzip compression, I found in CI config.php

    By default,
    $config['compress_output'] = False;
    But If I do
    $config['compress_output'] = True;
    Do I have to anything more?

    Add an Expiry Header

    Can I set Expiry Header in a config?
    I found that in download helper they add expiry header:

    // Generate the server headers
    if (strstr($_SERVER['HTTP_USER_AGENT'], “MSIE”))
    {
    header(’Content-Type: “‘.$mime.’”‘);
    header(’Content-Disposition: attachment; filename=”‘.$filename.’”‘);
    header(’Expires: 0′);
    header(’Cache-Control: must-revalidate, post-check=0, pre-check=0′);
    header(”Content-Transfer-Encoding: binary”);
    header(’Pragma: public’);
    header(”Content-Length: “.strlen($data));
    }
    else
    {
    header(’Content-Type: “‘.$mime.’”‘);
    header(’Content-Disposition: attachment; filename=”‘.$filename.’”‘);
    header(”Content-Transfer-Encoding: binary”);
    header(’Expires: 0′);
    header(’Pragma: no-cache’);
    header(”Content-Length: “.strlen($data));
    }

    So if I Use do download helper then do I change the value of :
    header(’Expires: “.gmdate(”D, d M Y H:i:s”, time()+600)” .” GMT”’);
    header(’Cache-Control: max-age=600′);
    can I set this things in config.php ?

    Making fewer HTTP requests and Config ETags:

    In your example you show , how to do fewer http request using . .htaccess to cache all the things.
    Can I Making fewer HTTP requests and Config ETags in config.php ?

  • Shiplu // September 26, 2007 at 2:03 am | Reply

    for /F %%F in (’dir /b *.js’) do java -jar custom_rhino.jar -c %%F > %%F.packed 2>&1
    What was your OS for this command?
    if its windows,
    what is the name of the quotes you have used here ’dir /b *.js’ ?
    let me know it in my mail please.
    It’ll help me.

  • Speed Up your Web Application by CodeIgniter « Saidur Rahman Bijon // May 3, 2008 at 3:29 pm | Reply

    [...] you have to focus that to High speed your web site performance. I have read a nice article" Performance tips for web applications" where focus the performance tips of web application. These tips can easily apply by [...]

  • Venu vasu // June 13, 2008 at 9:22 pm | Reply

    Its Really good

  • Scripting Lover // July 7, 2008 at 8:00 pm | Reply

    These are really practical and informative techniques. It will make your code clear and easy to modify and maintain.

  • sheryar nizar // August 26, 2008 at 1:32 pm | Reply

    ieeexplore.ieee.org/iel5/9341/29678/01348053.pdf

    is good link

  • Satish Patruni // January 27, 2009 at 8:19 pm | Reply

    Nice article and insight. Good to have bumped onto your blog and met you.

    Satish Patruni
    mynotesday2day.googlepages.com

  • asif // February 26, 2009 at 6:49 pm | Reply

    Although this article is old but very useful and still applicable and beneficial.

Leave a Comment