» Help

Check that a HTML document has completely loaded


Because the TWebBrowser control loads documents asynchronously, you often need to wait for the document to finish loading before continuing. For example, you'll have to do this if you need to work with the HTML document's IHTMLDocument2 interface, because that interface is not available until the document has finished loading.

Drop a TWebBrowser and a TButton control onto a Delphi form and add the following OnClick event handler to the button:

procedure TForm1.Button1Click(Sender: TObject);
  procedure Pause(const ADelay: LongWord);
    StartTC: DWORD;
    CurrentTC: Int64;
    StartTC := GetTickCount;
      CurrentTC := GetTickCount;
      if CurrentTC < StartTC then
        // tick count has wrapped around: adjust it
        CurrentTC := CurrentTC + High(DWORD);
    until CurrentTC - StartTC >= ADelay;
  while WebBrowser1.ReadyState <> READYSTATE_COMPLETE do
    Pause(5); // 5ms delay before re-testing

The code loads the DelphiDabbler website's home page into the browser control and does not return until the page is fully loaded. It simply tests the browser control's ready state and performs a busy wait until the READYSTATE_COMPLETE state is reached. The private Pause procedure simply performs the busy wait while allowing the rest of the program to remain responsive.

Author: Peter Johnson
Contributor: Peter Johnson
Added: 2009-06-17
Last updated: 2009-11-13

« Return to contents »