Thimble got a little version bump today and a new feature: Auto Refreshing.
Hit the little checkbox and when your theme has been updated, Thimble will refresh the preview.
Implementing this the way I wanted to was a bit of an experiment. Here’s how it works:
How it works
The preview is in an iframe. I did not want to just have the iframe refresh itself every X seconds, potentially interrupting the previewing experience. Rather, I wanted the preview to only refresh when the theme had changed.
Ideally, there would be some kind of magical event loop and when the theme changed, an updated preview would comet itself up to the browser, refreshing the preview. That’s hard, and requires some heavy lifting on the server and the client, and I’m not even sure PHP has a mechanism for “real-time” updates like this. Even solutions like Ruby’s EventMachine and Python’s Twisted are too complex for a tool that prides itself on simple setup.
So Instead, the client JavaScript is in charge of polling to see if the theme has changed. How does it do that? By using the natural cacheing idioms of HTTP:
function ThimblePoll(theme, iframe) {
$.ajax({
type: 'HEAD',
url: 'theme.php?theme='+theme,
ifModified: true,
success: function(data, status, xhr) {
if (status !== "notmodified") {
iframe.src = iframe.src;
}
THIMBLE_POLL = setTimeout(function(){
ThimblePoll(theme, iframe);
}, 5000);
}
});
return THIMBLE_POLL;
}
When ThimblePoll is called, it makes a HEAD request to the theme preview file, which has a Last-Modified HTTP Header. If the response is a 304 Not Modified, that means that the theme has not been updated. If it has been, only then is the preview updated. When you check the auto-refresh box, it’s not going to begin auto-refreshing, it only begins polling in the background until it gets a good response. And since these are HEAD requests, the overhead is minimal.
Some browsers might not like this cacheing approach. If you find you run into stickiness, clear your browser cache. Like anything I make, YMMV.