Tuesday, October 03, 2006

IE, Back button, AJAX and DHTML. Solution - exploit onload.

Most people know about the back button feature when developing heavy
AJAX web sites. That is not what this is about.

I created a simple web page to save favorite things. An image titled
"Save" or "Remove" appears on the screen depending if a favorite can be
saved or is saved. When pressed, a simple AJAX request is sent the
server and the images are swapped if the request is successful. I want
the appropriate button to appear no matter how one navigates to the
page. Unfortunately, in Internet Explorer, if I navigated away from the
screen and then 'back' to the page, all the images reverted back how
they were initially loaded -- all DOM changes are forgotten. Firefox
will display the latest DOM, so there are no problems here.

After playing around a little bit, I noticed that IE also runs the
'onload' function when you navigate 'back' to it and so I exploited
this. The onload runs an AJAX call to retrieve ones favorites and then
changes the image to the appropriate image. Since I used get requests,
I also had to append a time stamp to the end of the URL just before
'open' to avoid IE caching.

The advantage of doing this is that it works. The disadvantage is that
the logic is in the javascript and not the JSP.

No comments: