Search code examples
javascriptonclickcross-browserprototypejsdom-events

Handling browser native click before dom:loaded


I have an issue with Cross-Browser native events vs CallBack events.

I have an HTML link "Click Me" with a given href="". On dom:loaded I attach a function to this link (to do Ajax Stuff).

JavaScript code is loaded at the end of the page to follow YSlow Recommandation.

Issue:

If you load this page really quickly (pressing F5) then click on link then

  • the alert() is not called
  • the link is followed (reloading the page)

It happens when the server lags. In fact the page has not finished loading and the browser execute the code.

Demo:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
  </head>
  <body>

    <a href="#toolate" id="action">Click Me</a>

    <!-- According to YSlow Recommandation load at the bottom -->
    <script src="../js/lib/prototype.js" type="text/javascript" language="JavaScript"></script>
    <script>
      /* <![CDATA[ */
      document.observe('dom:loaded', function() { 
        $('action').observe('click', function(event){ alert("click"); Event.stop(event); });
      });
      /* ]]> */
    </script>
  </body>
</html>

Turn Around:

A turn around is to add onClick="return false;":

<a href="#toolate" id="action" onClick="return false;">Click Me</a>

It works for lags but not for quick click. And I don't like this kind of turn around because my goal is to remove the onclick on all <a href="">


Solution

  • We have done many many test on our CMS on many browsers.

    Sorted by speed:

    1. JavaScript can't execute before a really fast click
    2. onclick="return false" works fine in most case
    3. JavaScript doing 2.) onLoad is too slow but could be enought
    4. DIV using as shield brings other issues and is not a good choice