Why you should stop using onload method.

Onload
Onload

It is amazing that many web developers still use onload method embedded in the BODY tag, like


 <HEAD>
 <BODY onload="document.contact.userID.focus();">
  <form name="contact">
   <input type="text" name="userID" >
  </form>
  </BODY>
 </HEAD>

There are two problems with this line of code.

  1. Embedding code (behavior) with HTML (structure) makes it difficult to maintain the page.
  2. onload() method will executes only after the page is fully displayed.
  3. Let’s see how to fix these problems.
    Fixing problem # is quite simple. Just move your JavaScript code to the header section of you HTML page.

    
    <HTML>
    <HEAD>
    <script language="javascript">
    function setFocus(){
    	document.contact.userID.focus();
    }
    </script>
    </HEAD>
    <BODY onload="setFocus();">
    <form name="contact">
    <input type="text" name="userID" >
    </form>
    </BODY>
    </HTML>
    

    Even better approach would be to move the code to an external Javascript file and add a reference to that file in the header section of the HTML document. For example, if the code is in script.js you can import the code like

    
    <HTML>
    <HEAD><script language="javascript" ref="scripts/script.js">
    </HEAD>
    <BODY onload="setFocus();">
    <form name="contact">
    <input type="text" name="userID" >
    </form>
    </BODY><
    /HTML>
    

    This approach will make your HTML code clutter-free and the code will be more manageable. But this does not address the fact the there is a delay in the exectuion of the code. onload method executes after the page is completely loaded. For instance, if you want to set focus to a text field on your web page using onload method, the foucs will be set after the page is completly downloaded.

    If your web page is a simple text page with no images or multimedia elements then using onload might be OK. However, nowadays almost all web pages have at least few images, some even have embedded audio, video, Flash or other rich multimedia resources. These large resources take considerably long time to be fully loaded. And until all the content of the page is fully downloaded and the DOM tree is constructed, onload will not be fired.

    Set focus to the text field without onload:

    There is nothing wrong with the onload method, the problem is the large size of page elements that need to be downloaded by the browser. The browser needs to construct the DOM tree, load all the images and other multi-media resources and when everything is done then it will execute the onload method. A DOM tree is constructed instantly by the browser, but the large size of other elements take a while to be fully loaded. It means these external multilmedia files keep browser from executing the code triggred my onload event. The best approach would be to wait just long enough to let browser contstuct the DOM tree and then execute your code without waiting for all the objects to be completely downloaded. This can be done by using jQuery's ready() function.

    
      <script type="text/javascript" src="scripts/jquery-1.3.2.min.js">
      </script>
        <script type="text/javascript">
          jQuery(document).ready(function() {
            document.contact.userID.focus();
          });
        </script>
    

    or more formally.

    
    $(function(){
    	document.contact.userID.focus();
    }
    

    So now your HTML code will be like

    
     <HTML>
     <HEAD>
      <script type="text/javascript" src="scripts/jquery-1.3.2.min.js">
      </script>
        <script type="text/javascript">
          jQuery(document).ready(function() {
            document.contact.userID.focus();
          });
        </script>
     </HEAD>
     <BODY >
     <form name="contact">
     <input type="text" name="userID" >
     </form>
     </BODY>
     </HTML>
    

    Now our JavaScript code will be executed as soon as the DOM is fully constructed, without waiting for images and other multimedia resources. In this example the focus will be set to your input text field almost instantly and user can start typing in the information without waiting for rest of the page to be downloaded. This is a simple but effective way of improving your website's usability.


If you enjoyed this post, make sure you subscribe to my RSS feed!

Comments 9

  • I would like to underline the fact this post is amazing , you got me bookmarking your site!

  • Haven’t heard that yet. Where did you find this info from?

  • It’s amazing how many sites and tutorials don’t mention this. Extracting the Javascript and putting it into the head is imperative in this day and age. I feel sorry for people learning web design now who read from the outdated tutorials that still use the onload=”” technique.
    Thanks for sharing your knowledge!

  • 11. Wonderful day to you, I usually read your blog and that i am certainly one of your fan. I adore the way you talk to your reader as if they are your buddy.

  • Another one that thinks himself an expert in javascript but bases his teachings in a library that hides the details, and hence the library not you has the knowledge.

  • Or you can use autofocus.

  • [input type=”textfield” autofocus /]

  • First, I’d like to say that this post was very helpful all around.

    I’d like to say that the author is completely correct in that for large websites it is very inconvenient to have the textfield focus after the loading of the entire page.

    However, is this small and simple Javascript an inconvenience of web designers that have large amounts of data on their pages…

    … or is the large amounts of API code (Facebook widgets, Spry, JQuery, etc.) being inserted onto a page the larger problem?

    Even without this JavaScript, I find that there are too many websites that sloppily encoding APIs as small as AdSense and as bulky as ning and Facebook plug-ins directly into the code of pages and templates not realizing…

    … that it’s this code that is actually causing a loading problem.

    Either way, I’d recommend designers of large websites to really consider if this small onLoad code is your problem, or a robust amount of monetizing (advertisement) and overly-bulky code the real problem.

    @comment:

    EXCELLENT comment. Although keeping your code clean and neat is important at the end of your development, this “culture” of modularizing everything is causing a portion of developers to become “cookie cutter” learners, knowing what to implement where, but not exactly knowing why.

    @lothop

    While I bookmarked and REALLY LIKED this post…

    I LOVED your unassuming and ridiculously short post.

    I decided to implement your input tag “autofocus” suggestion and has been running faster compared to the body “autofocus” orginally discussed.

    KUDOS!

    Devil’s Hackvocate
    “Remember Oscar Grant”

  • We are done with our motorhome printed punctuation mark.
    It is important to research and investigate all your options; do not stop at the
    first sign of wearing off.

    Feel free to surf to my site: small bathroom renovations melbourne

Leave a Reply

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