Use clickCatcher to capture the Click event before the JS file is loaded/before the event Application

Source: Internet
Author: User
Tags website performance

One way To Improve website Performance is To put the JavaScript file at the bottom of the document (I discussed it in Improve Your Web Site Performance-Tips & Tricks To Get A Good YSlow Rating ). However, this has a disadvantage.

Problem

Before JavaScript files are loaded and run, you plan to allocate an event processor to some elements in the document. What happens if you click these elements at this time? Then the browser will execute the default behavior of the element. For example, a link that takes a user to another page is not intended to do so, but to dynamically load some information through AJAX or other methods.

Theoretical Solution

Recently, my colleague David Billskog and I have discussed and studied this problem. The solution is to include a JavaScript block (inline or encoded DED) in the header of the document ), and be sure to capture all the click events on the page. Then filter them to determine which element you are planning to apply the event processor.

Finally, when the page is loaded/the event processor has been allocated, remove the previously assigned clickCatcher, iterate all the elements clicked before this, and then trigger the real click events of these elements, triggers normal and Application Event behaviors.

Actual Solution

David and I started their work. For me, the solution does not require any JavaScript library, david's solution is based on jQuery (which can be easily applied to any other library ). I listed my solution-clickCatcher.

ClickCatcher uses some simple script functions as the basis:

  • AddEvent -- assign a click event to the document without overwriting any potentially assigned click Event processor.
  • RemoveEvent -- after the page is loaded, remove the events allocated above and stop capturing the clilck events.
  • FireEvent -- release the click events of all the clicked elements before the JavaScript file is loaded.

The clickCatcher

(function () {clickCatcher = function () {var clicks = [],addClicks = function (evt) {var classCheck = /catch/,body = /body/i,target = (evt.target)? evt.target : evt.srcElement;while (!classCheck.test(target.className) && !body.test(target.nodeName)) {target = target.parentNode;}if (classCheck.test(target.className)) {clicks.push(target);if (evt.preventDefault) {evt.preventDefault();}evt.returnValue = false;return false;}},callClicks = function () {removeEvent(document, "click", addClicks);for (var i=0, il=clicks.length; i<il; i++) {fireEvent(clicks[i], "click");};},init = function () {addEvent(document, "click", addClicks);// Could be called here, but now called manually in script loaded later - adapt to your situation//addEvent(window, "load", callClicks);};return {init : init,callClicks : callClicks};}();clickCatcher.init();return clickCatcher;})();

ClickCatcher is encapsulated in an anonymous self-called function, so that it will not be confused with the global variables of the web page, but create its own scope. If you want to access it elsewhere, this part of code can selectively expose the clickCatcher object itself. The Code attaches an event processor to the document. If the clicked element (or any of its parent elements) has a class name catch (such as a link), each click is stored in an array.

Once the page is loaded, you can make it automatically called, or you can manually trigger it by calling clickCatcher. callClicks;

The complete code that contains the addEvent, removeEvent, and fireEvent Methods looks like this:

// By Robert Nyman, http://robertnyman.com/clickcatcher/ - This content is released under the MIT License: http://www.opensource.org/licenses/mit-license.php(function () {// addEvent by John Resig, http://ejohn.org/blog/flexible-javascript-events/function addEvent( obj, type, fn ) {if ( obj.attachEvent ) {obj['e'+type+fn] = fn;obj[type+fn] = function(){obj['e'+type+fn]( window.event );}obj.attachEvent( 'on'+type, obj[type+fn] );} elseobj.addEventListener( type, fn, false );}function removeEvent( obj, type, fn ) {if ( obj.detachEvent ) {obj.detachEvent( 'on'+type, obj[type+fn] );obj[type+fn] = null;} elseobj.removeEventListener( type, fn, false );}// fireEvent by Jehiah Czebotar, http://jehiah.cz/archive/firing-javascript-events-properlyfunction fireEvent(element, event) {var evt;if (document.createEvent) {// dispatch for firefox + othersevt = document.createEvent("HTMLEvents");evt.initEvent(event, true, true ); // event type,bubbling,cancelablereturn !element.dispatchEvent(evt);} else {// dispatch for IEevt = document.createEventObject();return element.fireEvent('on'+event,evt);}}clickCatcher = function () {var clicks = [],addClicks = function (evt) {var classCheck = /catch/,body = /body/i,target = (evt.target)? evt.target : evt.srcElement;while (!classCheck.test(target.className) && !body.test(target.nodeName)) {target = target.parentNode;}if (classCheck.test(target.className)) {clicks.push(target);if (evt.preventDefault) {evt.preventDefault();}evt.returnValue = false;return false;}},callClicks = function () {removeEvent(document, "click", addClicks);for (var i=0, il=clicks.length; i<il; i++) {fireEvent(clicks[i], "click");};},init = function () {addEvent(document, "click", addClicks);// Could be called here, but now called manually in script loaded later - adapt to your situation//addEvent(window, "load", callClicks);};return {init : init,callClicks : callClicks};}();clickCatcher.init();return clickCatcher;})();

You can test the code on the clickCatcher page.

SetTimeout

However, whether it is to Trigger clicks execution from inside the clickCatcher or to manually call them, you must be sure that this is the final call. One interesting result of David's research is that you can use setTimeout to control the call stack and set time to 0. In this way, compared with other load event processors, it will be placed at the end of the stack.

That is to say, if you use addEvent to call something when the window has been loaded, you can control it like this (maybe only in the same script block or JavaScript file ).

// Calling click handlersetTimeout(function () {addEvent(window, "load", callClicks);}, 0);// My own function - will be called before the above functionaddEvent(window, "load", myCoolFunc);

JQuery version

Previously I mentioned the jQuery version of David, which means that jQuery must be included before you call it, but you can place other JavaScript files at the bottom of the page. He introduced his method and found the result in clickCatcher with jQuery.

Feedback?

We can see from our tests that capturing click events before JavaScript loading is complete is an effective and reliable method. You can still place js at the bottom of the document to improve website performance.

Original article address: Http://robertnyman.com/2010/05/24/catching-clicks-with-clickcatcher-before-your-javascript-files-have-loadedevents-been-applied? Utm_source = feedburner & utm_medium = feed & utm_campaign = Feed % 3A + Robert tnyman + % 28 Robert % 27 s + talk % 29

Reprint address: http://www.denisdeng.com /? P = 1018

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.