Question

When creating any site that uses JavaScript I usually hook into anchors for my click listeners. This is so that if JavaScript isn't supported or is turned off the site will still work for users. I put the majority of my script code at the end of the document near </body> so that the content is loaded first. The only exceptions being things like modernizr, google tracking code, etc.

However in doing this it means there is a time period in which anchors are present on the page in which time the user can interact with them before the JavaScript has loaded and attached event listeners.

I thought about adding some stubs to all the anchors but I can't figure out a way to make it work, considering that the anchors haven't been put on the page yet if my stub script is above the <body> element. I assume it's possible as the old jQuery live() function did something similar (I'm aware that's now deprecated 1.7 and removed 1.9).

The idea would be I create a do nothing stub for all interaction points. Point the interaction points to it whilst the page loads. Once everything has loaded remove the stubs and use the fully defined listeners.

Has anyone done this before... or got a better solution?

Was it helpful?

Solution

I assume it's possible as the old jQuery live() function did something similar (I'm aware that's now deprecated 1.7 and removed 1.9).

I think that's pretty close. It's been replaced with .on('EVENT', 'SELECTOR', FUNCTION).

You could use something like:

$(document).on('click', 'a', false); // disable all clicks

Then, once it's fully loaded, take the handler off:

$(document).off('click', 'a', false);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top