PageSpeed: A more controversial tip

This tip is based on an alternative -I think- not very known to load an image as a part of the HTML avoiding so another request to the server. When you write a label <img … > you cant put in the «src» attribute the content of an image (the content of the file) in Base-64 format. Let’s see an example:

<img src=»data:image/gif;base64,abcdef…» />

This technic is totally legal since long time ago, according to the RFC 2397. Maybe it felt in disuse because it doesn´t seems too optimal. But … I want to talk about «but».

If the cache acts over the HTML, acts also over the image. In a lot of situations, obviously not with lists, we have static content served as dynamic just to simplify the way we put some elements like menus in the HTML. In these cases, only one request will avoid further request for more content (neither HTML or images). I would use this technic only for icons which are files that usually doesn´t change.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<head>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
	<title>PageSpeed : Truco para subir nota</title>
	<link rel="stylesheet" type="text/css" href="csi/common.css" />
	<script type="text/javascript" src="csi/jquery-home.js"></script>
</head>
<body>

	<img src="<? ico("../images/contact.gif") ?>" />

</body>
</html>
<?

	function ico($file) {
		$b64 = base64_encode(rfile($file));
		$mt  = strpos("gif", $file) ? "image/gif" : "image/jpeg";
		$src = "data:{$mt};base64,".$b64;
		echo $src;
	}

	function rfile($filepath) {
		$text = "";
		if($file = fopen($filepath, "rb")) {
			while (!feof($file)) {
				$text .= fread($file, 8192);
			}
			fclose($file);
		} else {
			die("Couldn't read the $filepath.");
		}
		return $text;
	}

?>