Use of server side and browser side cache to optimise a configurable JavaScript code load time.

  • appid : unique id that references client
  • language : language chosen by the client
https://site.com/language/script.js?appid=xxxxxx
$currentversion = '1.0';
define("REDIS_SERVER","127.0.0.1");
define("REDIS_PORT",6379);
define('DEV_MODE',0);
include_once dirname(__FILE__) .DIRECTORY_SEPARATOR.'config.php';
include_once(dirname(__FILE__) .DIRECTORY_SEPARATOR.'init.php');
$mtime = explode(" ",microtime());
$starttime = $mtime[1]+$mtime[0];
$redis_file_key="script.$appid.$lang.js"
$redis_time_key= "time.".$redis_file_key;
ob_start();if(($redis->get($redis_file_key)!=false) && (DEV_MODE==0)){
if(!empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])&& (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])==$redis->get($redis_time_key))){
header("HTTP/1.1 304 Not Modified");
exit();
}
echo $redis->get($redis_file_key);
$js = ob_get_clean();
} else{include_once dirname(__FILE__). '/js/s1.js';
include_once dirname(__FILE__). '/js/s2.js';
$js = ob_get_clean();
$redis->set($redis_file_key,$js);
$redis->set($redis_time_key,time());
}
$lastModified = $redis->get($redis_time_key);
header('Content-type: text/javascript;charset=utf-8');
header("cache-control: public, no-cache");
header("Last-Modified: ".gmdate("D, d M Y H:i:s",$lastModified)." GMT");
header('Expires: '.gmdate("D, d M Y H:i:s",time()+3600*24*365).' GMT');
echo $js;$mtime = explode(" ",microtime());
$endtime = $mtime[1]+$mtime[0];
echo "\n\n/* Execution time: ".($endtime-$starttime)." seconds */";
https://site.com/en/script.js?appid=12542
if (defined('DEV_MODE') && DEV_MODE == '1') {
error_reporting(E_ALL);
ini_set('display_errors','On');
}
$appid=$_REQUEST["appid"]??"";
$lang=$_REQUEST["language"]??"en";
include_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'languages'.DIRECTORY_SEPARATOR.'en.php');if (file_exists(dirname(__FILE__).DIRECTORY_SEPARATOR.'languages'.DIRECTORY_SEPARATOR.$lang.'.php')) {
include_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'languages'.DIRECTORY_SEPARATOR.$lang.'.php');
}
$redis = new Redis();
$redis->connect(REDIS_SERVER, REDIS_PORT);
$redis->select(1);
/** check if browser support websockets **/    
if(check_websocket()===false){
this.errorEvent("<?=$language[6]?>");
$.gui_engine.alert("<?=$language[10]?>","<?=$language[6]?>");
return;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mohamed Gaddour

Mohamed Gaddour

Certified :Associate Android Developer, Zend Certified PHP Engineer, LPI Devops, LPIC 1, ITIL.