title: How can I wait for the page to be ready in PhantomJS?
body: <p>I'm using PhantomJS to log into a site an do something. The site used OAuth for logging in. Clicking on the "Login" button on the, takes you to the OAuth service. There you enter your credentials and clicking "Submit", you get redirected back to the original site. My script works fine but relies on timeouts which doesn't seem too robust. </p>
  
  <p>How can I rewrite this code so that instead of using <code>setTimeout</code>, I can wait until the page is ready. I often see errors that the page isnt' ready and therefore jQuery isn't initialized.</p>
  
  <p>I'm not too good with Javascript so an example would be helpful. This is what I've hacked together after a ton of Googling. Here's my code:</p>
  
  <pre><code>var page = require('webpage').create();
  var system = require('system');
  
  page.settings.resourceTimeout = 10000;
  page.onResourceTimeout = function(e) {
    console.log("Timed out loading resource " + e.url);
  };
  
  page.open('https://mysite.com/login', function(status) {
      if (status !== 'success') {
          console.log('Error opening url');
          phantom.exit(1);
      } else {
          setTimeout(function() {
              console.log('Successfully loaded page');
              page.evaluate(function() {
                  $("#submit-field").click(); //Clicking the login button
              });
  
              console.log('Clicked login with OAuth button');
              setTimeout(function() {
                  console.log('Addding the credentials');
                  page.evaluate(function() {                
                      document.getElementById("username").value = 'user@example.com';
                      document.getElementById("password").value = 'P@ssw0rd';
                      document.getElementById("Login").click();
                  });
                  console.log('Clicked login button');
  
                  setTimeout(function() {
                      //Inject some jQuery into the page and invoke that here
                      console.log('Clicked the export button');
                  }, 15000);
              }, 15000);
          });
      }
  });
  </code></pre>