Clickcatcher proof of concept

Problem

If you add behaviour to links with javascript and the page is slow to load. Clicking a link will break the page.

Example

Say we have a link.

  1. <a class="js-link" href="http://www.example.org">Magic link</a>

We want to display an alert box when this link is clicked. So we add this script to the bottom of the page.

  1. // slow-request.js (will take 5 seconds to load)
  2. $(document).ready(function () {
  3.   $('.js-link').click(function() {
  4.     alert("success!");
  5.     return false;
  6.   });
  7. });

For a slow loading page, this is implementation has a problem.

problem-visualized

Solution

Put dangerous click events on hold until the document is fully loaded.

  1. (function () {
  2.   var QUEUE = {
  3.     clicks : [],
  4.     click_handler : function (evt) {
  5.       if ($(evt.target).hasClass("guarded")) {
  6.         QUEUE.clicks.push({
  7.           evt : evt,
  8.           target : evt.target
  9.         });
  10.         return false;
  11.       }
  12.       return true;
  13.     }
  14.   };
  15.   $(document).bind("click", QUEUE.click_handler);
  16.   $(document).ready(function () {
  17.     // setTimeout make sure this function is executed after everthing
  18.     // else when load is triggered.
  19.     setTimeout(function () {
  20.        $(document).unbind("click", QUEUE.click_handler);
  21.        for (var i=0, il=QUEUE.clicks.length; i<il; i++) {
  22.          $(QUEUE.clicks[i].target).click();
  23.        }
  24.     }, 0);
  25.   });
  26. })();

(This script will need to be loaded as early as possible.)

Demo

Classic behaviour With the clickcatcher script

Disclaimer

You would probably do not want to load the jquery library at the top of your page if you can avoid it.