Here is an AppleScript to check if the foremost window in Safari has finished loading the requested page. Some people have suggested using a do javascript solution way, and I know there are hints like this out there, but this seems to be the only bulletproof way to do things.
How does it work? Well, when you click on a link or request a page in Safari, the Safari status bar will always display the text Contacting... and subsequently Loading.... However, it seems not everyone knows how to access that text within AppleScript. So, here's how I did it:
--check if page has loaded
repeat
delay 0.5
tell application "System Events" to ¬
tell application process "Safari"
if (name of static text 1 of group 1 of window 1 as text) ¬
begins with "Contacting" or (name of static text 1 of group 1 ¬
of window 1 as text) begins with "Loading" then
else
exit repeat
end if
end tell
end repeat
That code will basically run until the page is done loading in Safari -- hooray for infinite loops! You can make it into a subroutine, if you'd like. I'm sure there are other ways to use the status bar information, too.
Mac OS X Hints
http://hints.macworld.com/article.php?story=20071015132722688