JavaScriptRefresh

From XPUB & Lens-Based wiki

An example of using javascript to reload a (script-generated) image. See the result

First a simple PHP script that generates an image with a URL-specified text:

A Dynamic Image

image.php

<?php
header ("Content-type: image/png");
$t = $_GET['t'];
if (!isset($t)) $t = "Hello world!";
$im = @imagecreatetruecolor(200, 20)
      or die("Cannot Initialize new GD image stream");
$c = imagecolorallocate($im, 255, 0, 0);
imagestring($im, 1, 5, 5,  $t, $c);
imagepng($im);
imagedestroy($im);
?>

This example is based upon example code from the PHP reference.

The Containing Page & Browser Script

And now, the HTML / JavaScript that displays the image, and each second reloads the page (with a timestamp). NB: the use of the timestamp is to ensure that the browser reloads the image -- even if the image were not displaying the current time, this technique requires that the timestamp be present so that the URL keeps changing (and thus is never "cached" or ignored.

refreshing.html

<?xml version="1.0" encoding="ISO-8859-1"?>
<!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="en" lang="en">
<head>
<title>My page title</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script language="JavaScript" type="text/javascript">
// <!--
	// THE REFRESH FUNCTION
	function myrefresh() {
		var img = document.getElementById("refreshme");
		var now = new Date();
		var newsrc = "image.php?t=" + escape(now.toLocaleString());
		// console.log(newsrc);
		img.src = newsrc;
		// call me back in 1 second
		window.setTimeout(myrefresh, 1000);
	}
// -->
</script>
</head>
<body onload="window.setTimeout(myrefresh, 1000);">
<h1>how refreshing</h1>

<!-- THE IMAGE TAG -->
<img id="refreshme" src="image.php" />

<p>
Using meta refresh for redirection is considered by the W3C to be a poor practice, since it does not communicate any information about either the original or new resource to the browser (or search engine). Many web design tutorials also point out that client side redirecting tends to interfere with the normal functioning of a web browser's "back" button. After being redirected, clicking the back button will cause the user to go back to the redirect page, which redirects them again. Some modern browsers seem to overcome this problem however, including Safari, Mozilla Firefox and Opera. Others, like IE, can be "tricked" by doing two rapid clicks of the "back" button - the first lands you on the redirect page, and before the time interval expires the second click takes effect to land you on the previous page. The use of zero delay redirects may cause the two rapid clicks technique to be impossible.
<br />
<i><a href="http://en.wikipedia.org/wiki/Meta_refresh">wikipedia</a></i>
</p>
</body>
</html>