Load Javascript Files using a PHP file

To increase the performance and reduce the loading time of a web page, we need to minimize the http request to the server. In a web page we may call many javascript files externally, which may takes more time to load the page.

To reduce http request you may put all the scripts in a single javascript file and call within the page. But the page size will become higher and maintenance, and reusing the script files will be an issue.

So, we can keep the javascript files separately and can write a php file to load the javascript files as follows. We followed this way and got a better results .

Place the following script within bottom of the page

src="http://yourserver.com/javascripts/load_index.js.php"
set the above src correctly within script tag as a normal javascript external call.



Create a php file ("load_index.js.php")

$jsfile = array('abc1.js','abc2.js','abc3.js','xyz1.js','xyz2.js','xyz3.js','test1.js','test2.js','test3.js');
$full_js = "";
$js_load_path = "/data/javascripts/"; // file path
for($n=0;$n
$fh = fopen($js_load_path.$jsfile[$n], 'r');
$theData = fread($fh, filesize($js_load_path.$jsfile[$n]));
$full_js = $full_js . " ". $theData;
fclose($fh);
}
echo $full_js;




This method works in all browsers. We can reduce multiple http calls into single http call.