Wednesday, March 29, 2006

JavaScript Utility for Fixing URLs

Yesterday, I cancelled my dial-up ISP account. If you've been through the change-of-ISP experience, you know it can be tedious. I forwarded my email to a new account and I dutifully notified dozens of people and companies about my new email address. The last problem to solve was moving the many images stored on the web space provided by my old ISP. I've posted many Runtime Log entries that refer to those images. To avoid broken links in my blog's archives, I had to move the images to a new home.

Actually, the easy part was copying the image files to a new location on the web. The harder part was figuring out how to fix the references to those images in old posts. I could have edited each post by hand, but that would have been tedious and error prone. Even worse in my estimation is the edits would have caused Blogger to update my RSS feed. The old posts would look like they had been updated, when in fact I had just changed a URL or two.

I decided a better approach would be to leave the old posts alone and fix image URLs as each blog page is loaded into the browser. With help from a friend (thanks, Terry!), I wrote a few lines of JavaScript. The code is in a file called fixer.js.

To execute the code, I made two changes to my blog template. I added a <script> tag to the header:
<script type="text/javascript" src="http://mysite/fixer.js" />

Then I added an onload attribute to the <body> tag:
<body onload="fixImagesAndLinks('oldsite', 'mysite')">

Voila! The old URLs are now magically fixed. In a way, this is a kludge. I wouldn't recommend this approach for a production web application, but this is just a hobbyist-type blog. Sometimes a kludge is the right tool for the job.
 

No comments: