Prevention of links before loading jQuery


How can I prevent click event references before loading jQuery?
The reason is because I have several links that make AJAX calls through the jQuery ajax functions, and if the user clicks on them before the jQuery structure is loaded by the jQuery ajax function to launch the browser, and follows the href = "links ..." Thanks.

Edit: can i use this?

<head> ... <script type="text/javascript"> window.onload = prevCl(); function prevCl() { var links = document.links[]; links.onclick = check(); } function check() { if (typeof jQuery == 'undefined') { return false; } } </script> </head> 
+6
javascript jquery ajax javascript-events onclick
source share
3 answers

Four options for you:

Option 0

Read the answer of Sean Hogan , he noted that this can be done with the delegation ( doh! ), And I put together an example implementation.

Option 1

You can href "#" links before loading jQuery, and then (if necessary) change it to what it really should be. You can save what should be href in the data- attribute, for example:

 <a href='javascript:;' data-href='realtarget.html'>blah</a> 

Then:

 jQuery(function($) { $("a[data-href]").each(function() { var $this = $(this); $this.attr("href", $this.attr("data-href")); }); }); 

Again, the last bit, only if you really need to do href href. If you are processing a click on JavaScript, not necessary.

If validation is an important part of the development cycle, it is important to note that attributes in the form of data-xyz are invalid in HTML4 and earlier (browsers really don't care, but again, if you use validation ...). They become valid with HTML5.

Option 2

Use the onclick built-in attributes to intercept a click before loading jQuery and basically say "Sorry, one moment." So, in the script tag to the top of your file:

 function sorryLoading() { alert("Sorry, the page is still loading, one moment please."); return false; } 

... and then follow the links:

 <a href='realtarget.html' class='sorry' onclick='return sorryLoading();'>blah</a> 

... then remove onclick when jQuery loads:

 jQuery(function($) { $("a.sorry").removeClass('sorry').attr("onclick", "").click(yourRealClickHandler); }); 

(You can leave the last bit - click call - off, if they do not all have the same click handler.)

I used the class above to distinguish between these links and others that may have a built-in onclick (otherwise it is surprising that the "[onclick]" selector works on Chrome, Opera and Firefox for Linux and IE6 and IE8 on Windows).

Option 3

Since it seems like you want the page to be dysfunctional before loading jQuery, here is another approach:

  • Make sure the script tag for jQuery is in the head section of your page (and not at the bottom, where I usually recommend placing it).
  • At the very bottom of your page, before closing the body tag, jQuery.ready click handlers without jQuery.ready them in a jQuery.ready call (or any of its shortcuts).

The reason is this: # 1 will guarantee that jQuery itself will be loaded to the displayed page, and # 2 will connect handlers as soon as possible. Google recommends using the tag at the end of this page (rather than the ready function or similar) and says that at this point the DOM elements will be ready to be detected.


Separately, of course, you want to make sure that the time during which the links do not do what the user expects is as short as possible , you can perform all the functions of optimizing page loading. By clicking on the link and not having it, it looks as if it is making a bad user interface.

+9
source share

You can use delegation: the DOM equivalent of jQuery live () and delegate () .

The following may work:

 <head> <script> function linkMatcher(node) { // modify this if not all links are disabled if (node.href) return true; else return false; } document.onclick = function(e) { e = e || window.event; var target = e.target || e.srcElement; for (var node=target; node!=document; node=node.parentNode) { if (node.tagName == "A") return !linkMatcher(node); } } </script> </head> 

EDIT. This disables links forever. They can be re-enabled by removing the event handler, for example. document.onclick = null .


The complete, lively example below works on Chrome, Opera, and Firefox for Linux, as well as IE6 and IE8 for Windows. This prevents clicks on links with the "wait" class (you could use all links if you want), and remembers the first link. Then it simulates a long loading delay (five seconds), and then it connects jQuery handlers by links and removes the document level handler that prevents clicks, and then launches the jQuery handler on the link that was clicked (note that these are only triggers handler, and not the main default behavior - but since you want to run your ajax stuff, I assume that everything is fine). - TJ Crowder

HTML:

 <!DOCTYPE html> <html> <head> <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <meta charset=utf-8 /> <title>Link Click Delay Test Page</title> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <style> article, aside, figure, footer, header, hgroup, menu, nav, section { display: block; } body { font-family: sans-serif; } p { margin: 0px; } </style> <script type='text/javascript'> // A scoping function to avoid creating global symbols (function() { // Figure out what to hook clicks on var container = document.body || document.documentElement || document; // Hook clicks that reach the bottom level hookClicks(); function hookClicks() { if (container.attachEvent) { container.attachEvent("onclick", handleClick); } else if (document.addEventListener) { container.addEventListener("click", handleClick, false); } } // Set up an unhook function for jQuery to call window.unhookClicks = unhookClicks; function unhookClicks() { if (container.attachEvent) { container.detachEvent("onclick", handleClick); } else if (document.addEventListener) { container.removeEventListener("click", handleClick, false); } } // Handle clicks function handleClick(event) { var target; // Handle Microsoft vs. W3C event passing style event = event || window.event; // Get the target (again handling Microsoft vs. W3C style) target = event.target || event.srcElement; // Do we have a target that an A with the class "wait"? if (target && target.tagName.toUpperCase() === "A" && (" " + target.className + " ").indexOf(" wait ") >= 0 ) { // It a link we want to prevent for the moment // Remember the element that was clicked if there // isn't already one (or replace it, depends on the // UX you want to provide if (!window.pendingLink) { window.pendingLink = target; } // Prevent it from being processed if (event.preventDefault) { // If W3C method... event.preventDefault(); } // This should work if preventDefault doesn't return false; } } })(); </script> </head> <body> <p><a href='http://www.google.com' class='wait'>Google</a> - This one waits <br><a href='http://news.bbc.co.uk' class='wait'>BBC News</a> - This one also waits <br><a href='http://www.cnn.com'>CNN</a> - This one doesn't wait, it goes immediately </p> </body> </html> 

JavaScript (wherever the jQuery ready handler is located):

 jQuery(function($) { // Use setTimeout to fake a long delay loading setTimeout(function() { // Hook up our proper click handling // Obviously, replace this with whatever does the ajax $("a.wait").click(function(event) { alert("The jQuery handler for " + this.href + " link was triggered."); }); // If we have clicks disabled, enable them if (window.unhookClicks) { window.unhookClicks(); window.unhookClicks = undefined; } // Do we have a pending link to follow? if (window.pendingLink) { // Yes, grab it and clear it var $link = $(window.pendingLink); window.pendingLink = undefined; // Trigger any jQuery event handlers on it. // Note that this will NOT follow the link, // just trigger jQuery event handlers that // are on the link. $link.click(); } // We've loaded! $("<p>Finally loaded!</p>").appendTo(document.body); // End of fake delay function }, 5000); });​ 
+4
source share

I have not tried, but theoretically add a non-jquery event handler to all elements that prevent the default action (by opening a link) while jquery is not limited?

 getElementsByTagNames('a').addEventListener('click',function (event) { if (typeof jQuery == 'undefined') { event.preventDeafault(); } },false) 
+1
source share

All Articles