Home > General > Generating cache-friendly URLS for parallel image loading

Generating cache-friendly URLS for parallel image loading

February 24, 2008

The use of parallel image loading to improve page load time has been documented in multiple places. One of the key things to understand when one is using this technique is to always generate the same URL for the same static asset even if it resides on a different page.

This will allow the end-user to take advantage of HTTP proxy caches.

I wrote these set of simple PHP functions to demonstrate how one could incorporate this when generating the container HTML page for a website which uses parallel static asset loading

<?php
function path_to_origin_suffix($path,$NUM_ALIASES=2)
{
 /** Take hex value of md5 of $path. Get the ord value of the last
     hex char. Output it mod $NUM_ALIASES
 **/
 if (1 == $NUM_ALIASES)
     return 0 ;
 $hex = md5($path);
 return ord($hex[31]) % $NUM_ALIASES;
}

function make_url($path,$scheme="http",$origin="static.example.org")
{
 /**
    Add leading slash to $path. Generate suffix to append to basic
hostname
    basic hostname is the phrase before the 1st '.' in $origin
    Output a fully qualified URI encased in double quotes ""
 **/

 $pos = strpos($path,'/');
 if ($pos === FALSE || $pos != 0) {
  $path = sprintf('/%s',$path);
 }
 $suffix = path_to_origin_suffix($path);
 $array= explode('.',$origin,2);
 $host = "$array[0]$suffix.$array[1]";
 $abs_href = "$scheme://$host$path" ;
 echo "\"$abs_href\"";
}

function test() {
 echo make_url("/here/is/foobar") , "\n" ;
 echo make_url("here/is/foobar"), "\n" ;
 echo make_url("/there/is/foobar") , "\n" ;
 echo make_url("/there/was/never/a/foobar"), "\n" ;
 echo make_url("/please/mee/it/54"), "\n" ;
}

//test();
?>
   <html>
   <head><title>Parallel Static Asset Loading</title></head>
   <body>
   <img src=<?make_url("/john/rambo.gif")?> />
   <img src=<?make_url("here/was/john/rambo.gif")?> />
   </body>
   </html>

Hope this helps

About these ads
Categories: General
Follow

Get every new post delivered to your Inbox.

Join 1,198 other followers

%d bloggers like this: