<head>
  <script src="jquery.js"></script>
  <script>
    $(document).ready(function() {
      if (!("autofocus" in document.createElement("input"))) {
        $("#q").focus();
      }
    });
  </script>
</head>
<body>
  <form name="f">
  <input id="q" autofocus>
  <input type="submit" value="Go">
</form>
</body>

jQuery fires its custom ready event as soon as the page DOM is available — that is, it waits until the page text is loaded, but it doesn’t wait until all the images are loaded. This is not an optimal approach — if the page is unusually large or the network connection is unusually slow, a user could still start interacting with the page before your focus script executes. But it is still far better than waiting until the window.onload event fires.

← back to Dive Into HTML5