Wait for website to finish loading before continuing

Hey all,
Does anyone know of a reliable way to have a script wait for a website to finish loading 100% before proceeding? (using latest Safari 10)
I have been using delays, but it has to constantly be adjusted up and down until I find a sweet spot that works most of the time. But if the website is under heavy traffic my delays are useless.

I’ve searched high and low for solutions online, and most answers are years old and do not work.
Some use javascript to check if website is done, others try and check for content that loads at the end.

Does anyone know a modern solution to this issue?

Thanks in advance.

I have good success periodically checking the html source code until “” is found.

I’ve been using a method to try and click something on the page, and if it can’t, delay and repeat the try.

But not all websites have something I would want to click on for this to work most universally.

Example:

repeat
							try
								--try to select the name field area
								tell application "System Events"
									tell process "Safari"
										activate
										select button 2 of group 1 of group 6 of group 18 of UI element 1 of scroll area 1 of group 1 of group 1 of tab group 1 of splitter group 1 of window 1
										exit repeat
									end tell
								end tell
								-- if it cant, then delay and try again
							on error
								delay 0.5
							end try
						end repeat

Hi,

you could use javascript (you have to enable “Allow JavaScript from Apple Events” in Safari’s debug menu)

tell application "Safari" to open location "http://macscripter.net"
if waitForPageLoaded(20) then
	say "loaded"
else
	say "failed"
end if

on waitForPageLoaded(timeoutValue) -- in seconds
	delay 1
	repeat with i from 1 to timeoutValue
		tell application "Safari"
			if name of current tab of window 1 is not "Loading" then exit repeat
		end tell
		delay 1
	end repeat
	if i is timeoutValue then return false
	tell application "Safari"
		repeat until (do JavaScript "document.readyState" in document 1) is "complete"
			delay 0.5
		end repeat
	end tell
	return true
end waitForPageLoaded