Thursday, August 11, 2011

Make cache-friendly image path

A content delivery network or content distribution network (CDN) is a system of computers containing copies of data placed at various nodes of a network. When properly designed and implemented, a CDN can improve access to the data it caches by increasing access bandwidth and redundancy and reducing access latency. The price of this service is quite high, so it is not common for normal user.

However, if you can add more alias for your domain, your web page download speed can also be improved. For example,

http://static0.yourdomain.com/images/yourimage1.jpg
http://static1.yourdomain.com/images/yourimage2.jpg
http://static2.yourdomain.com/images/yourimage3.jpg
http://static3.yourdomain.com/images/yourimage4.jpg

Here is the function for making cache-friendly image path,

PHP:
function path_to_origin_suffix($path,$NUM_ALIASES=6){
    if (1 == $NUM_ALIASES)
        return 0 ;
    $hex = md5($path);
    return ord($hex[31]) % $NUM_ALIASES;
}


function make_url($path,$origin="static.yourdomain.com"){

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

    $abs_href = "http://$host$path";
    echo $abs_href;
}

Usage:
<img src="<?=make_url('/images/yourimage.jpg')?>">

This function is using MD5 to transform image path to hex value, and using ord to change to decimal number. Then, determine which alias domain should be used by MOD value

Javascript:
function make_url(path, origin) {
  
    if (typeof origin == "undefined") {
        origin = "static.yourdomain.com";
    }
  
    var pos = path.indexOf("/");
    if (pos == -1 || pos != 0) {
        path = "/"+path;
    }
    var suffix = (path.length+1) % 6
    var array= origin.split(".");
    var subDomain = array.shift();
    var domain = array.join(".");
  
    var host = "";
    host = subDomain+suffix+"."+domain;

  
    abs_href = "http://"+host+path;
    return abs_href;
}
Usage:
make_url('/images/yourimage.jpg')

Since there is not MD5 build-in function for Javascript, I just simply using the length of URL to determine which alias domain should be used.

Flash Actionscript 2:
function make_url(path, origin) {
    var origin = origin==undefined ? origin="static.yourdomain.com" : origin;
   
    var pos = path.indexOf("/");
    if (pos == -1 || pos != 0) {
        path = "/"+path;
    }
    var suffix = (path.length+1) % 6
    var array= origin.split(".");
    var subDomain = array.shift();
    var domain = array.join(".");
   
    var host = "";
   
    host = subDomain+suffix+"."+domain;
   
    abs_href = "http://"+host+path;
    return abs_href;
}

At last, please be careful that cross-domain issue after using this function to modify your JS path or SWF path.
Related Posts Plugin for WordPress, Blogger...