why does this work sometimes and sometimes not?

I am using some standard script I see often here for checking a Safari page load status:


on page_loaded(timeout_value)
	repeat with i from 1 to the timeout_value
		tell application "Safari"
			if (do JavaScript "document.readyState" in document 1) is "complete" then
				exit repeat
			else if i is the timeout_value then
				display dialog "Timed out"
				exit repeat
			else
				delay 1
			end if
		end tell
	end repeat
end page_loaded

It seems it works ok sometime, but if a page that safari is loading is slow… Meaning the “loading” blue bar in the browser address has only reached the “S” in HTTPS://www.etcyaddayadda.com it returns a “complete”.
Has anybody else had this and is there a modification to the script that could correct it.

The problem is that the page hasn’t started loading yet. Safari is still in the process of resolving the hostname in DNS so technically the page is ‘complete’ because Safari isn’t yet ready to update it.

Off hand, the simplest fix I can think of is to check the URL of the page to see if it’s the page you expect. ‘URL of document 1’ will return the URL of the currently visible page which will be an empty string if the window is new, or the URL of the previous page if you’re changing the page.

I wonder if your simple fix would work from what I am seeing. I see the URL change in the URL address bar and the page starts to load, but slowly.

I don’t know the exact URL name of where the page is going to because the server will select it based on form input information of the page I was on. I am not leaving the domain I am in, so I don’t think it is a DNS problem as much as a server side issue with things going while the server processes data.

I don’t think that comparing of the URL that was sucessfully loaded to the URL in the browser bar that is attempting to load would work, since I believe applescript sees them as different (I could be wrong here because I have not tested this).
Exmample:
set page url to x
Load next page
compare x to next page URL.

Any brilliant ideas on this?