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

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 HTML 5