Jeremy Stein - Brain

« »

Never use onload

Beware the body onload event. If you use it to trigger Javascript that needs to run before the user begins interacting with your site, you may be sorry. The problem is that it doesn’t fire until all the included content is also loaded (e.g. images). I’m sure it works fine for you, since you’ve already been to your site and the images are cached. But it may take a couple seconds (or longer for dial-up users) before the images load for everyone else. They’ve already started typing in the form when your Javascript fires and destroys their work.

My bank uses the body onload attribute to call Javascript that gives focus to the account number text box. However, by the time all their images load, I’m already typing my password. The focus jumps back to the account number text box and I enter half my password in clear text. This does not make me happy.

To their credit, when I complained about this, they fixed it and changed their Javascript to this:

//function gives focus to box if the user hasn't
//already typed something in the box.
function givefocus() {
  if (document.Login.userNumber.value == ''
      && document.Login.password.value == '')
    document.Login.userNumber.focus();
}

There’s another simple way to deal with this. Simply put your Javascript at the end of the page. For most cases, this will work just as well and will execute immediately, before loading images.

<html>
  <head>
    <script language="javascript">
      function init() {
        // Do stuff
      }
    </script>
  </head>
  <body>
    Content here
    ...
    <script language="javascript">
      init();
    </script>
  </body>
</html>

April 11, 2006 No Comments.

No Comments

Be the first to comment!

Leave a Reply

Your email address will not be published. Required fields are marked *

Why ask?

« »