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.
- <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.
- // slow-request.js (will take 5 seconds to load)
- $(document).ready(function () {
- $('.js-link').click(function() {
- alert("success!");
- return false;
- });
- });
For a slow loading page, this is implementation has a problem.
Solution
Put dangerous click events on hold until the document is fully loaded.
- (function () {
- var QUEUE = {
- clicks : [],
- click_handler : function (evt) {
- if ($(evt.target).hasClass("guarded")) {
- QUEUE.clicks.push({
- evt : evt,
- target : evt.target
- });
- return false;
- }
- return true;
- }
- };
- $(document).bind("click", QUEUE.click_handler);
- $(document).ready(function () {
- // setTimeout make sure this function is executed after everthing
- // else when load is triggered.
- setTimeout(function () {
- $(document).unbind("click", QUEUE.click_handler);
- for (var i=0, il=QUEUE.clicks.length; i<il; i++) {
- $(QUEUE.clicks[i].target).click();
- }
- }, 0);
- });
- })();
(This script will need to be loaded as early as possible.)
Demo
Classic behaviour- Expected behaviour for a click during the first 5 seconds is to be taken to www.example.org
- Expected behaviour after 5 seconds is an alert with the text "success!"
- Expected behaviour for a click during the first 5 seconds; delay the click to the fifth second then display an alert with the text "success!"
- Expected behaviour after 5 seconds is an alert with the text "success!"
Disclaimer
You would probably do not want to load the jquery library at the top of your page if you can avoid it.