Web page elements loading, interactive, or complete

Applescript appears to lack methods to listen to the state of a Web page fully loading its elements. As loading web elements occurs erratically and asynchronous to the Applescript timing, this interaction often runs afoul of Applescript’s execution.

To remedy this asynchonocity, a delay command can be inserted, to allow web elements to load, before Applescript continues to execute. This however leads to erratic delays and, when the delay command time in Applescript is too short , results in errors.

I wrote the following javascript based Applescript to provide a more effective approach to asynchronous web element loading, interaction and completion. The repeat block loops through three states of javascript’s ready states of “loading”, “interactive”, and “complete”.
The function of readystate calls the javascript command “document.readyState”, and exits should the target state be found within 5 repetitions. If the target state is found, then the loop exits for that specific readystate and proceeds to the next, that is to say, from “loading” to “interactive” to “complete”.

set ReadyStateList to {"loading", "interactive", "complete"}
repeat with aReadyState in ReadyStateList
	(my readystate:aReadyState)
end repeat

on readystate:readyStateStatus
	log readyStateStatus
	set NewReadyStateStatus to missing value
	set JS to "document.readyState"
	tell application "Safari"
		repeat with i from 1 to 5
			set NewReadyStateStatus to do JavaScript JS in document 1
			log NewReadyStateStatus
			if NewReadyStateStatus is readyStateStatus then
				exit repeat
			else
				log i
				delay 0.2
			end if
		end repeat
	end tell
	NewReadyStateStatus
end readystate:

I welcome any improvements or alternatives to this script.