How to execute code whenever Back button is pressed?

December 1, 2008

So I’d like to execute some JavaScript every time the page loads, regardless of whether it’s from a new visitor, or click of Reload, or a click of Back, or whatever.  However, I’m finding Back to be particularly tricky.  Here’s the test code:

<html>
<body onload="alert('Hello world!');">
    <a href="link">link</a>
</body>
</html>

Nothing fancy there, should pop an alert box every time right?  Wrong: click on the link and then click Back, and the alert doesn’t show.  (At least, not on Ubuntu 8.04 Firefox 3.)  Odd. 

Even stranger, it *does* show if you include a large (~100KB) external script:

<html>
<head>
    <script type="text/javascript" src="jquery.js"> </script>
</head>
<body onload="alert('Hello world!');">
    <a href="link">link</a>
</body>
</html>

But try it with a small (~4KB) external script and it stops working.  The mystery deepens.

The only explanation that makes sense is there must be some kind of delay when the page loads for the Back button to trigger the onload event.  Too small a delay (too small a file to load) and it doesn’t work.

Any ideas how to reliably execute code on every load, including Back?  I’ll use the jQuery trick for now, but I’m concerned that it won’t always be reliable.

Update: Curtis figured it out: It’s due to fancy Firefox caching rules. There are several criteria that go into whether the page is reloaded each time, one of which is whether there’s an “unload handler”. Turns out it wasn’t the *size* of including jQuery, it was due to jQuery setting an unload handler. Anyway, of the many solutions, the easiest is to simply set “Cache-Control: no-store” (or “no-cache”, if HTTPS). Thanks Curtis, mystery solved!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: