Last active
March 30, 2020 14:05
-
-
Save thexmanxyz/541c4f4040fa327ce0eb7d18ec861b47 to your computer and use it in GitHub Desktop.
Asynchronous Google reCAPTCHA loading, jQuery plugin: https://github.com/thexmanxyz/Async-Google-reCAPTCHA
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// you probably also want to prevent container resizing | |
// please use this CSS which works fine with the default v2 reCAPTCHA: .g-recaptcha { height: 78px; min-height: 78px; } | |
var loadRecaptchaAsync = function() { | |
// determine if container is in viewport | |
// you might pass an offset in pixel - a negative offset will trigger loading earlier, a postive value later | |
// credits @ https://stackoverflow.com/a/33979503/2379196 | |
var isInViewport = function($container, offset) { | |
var containerTop = $container.offset().top; | |
var containerBottom = containerTop + $container.outerHeight(); | |
var viewportTop = $(window).scrollTop(); | |
var viewportBottom = viewportTop + $(window).height(); | |
return containerBottom > viewportTop && containerTop + offset < viewportBottom; | |
}; | |
var loadRecaptcha = function() { | |
// only load reCAPTCHA if reCAPTCHA container is empty and container is in viewport (prevent double loading) | |
if (!$.trim($(this).html()) && isInViewport($(this), 0)) { | |
// async loading of reCAPTCHA library | |
jQuery.getScript("https://www.google.com/recaptcha/api.js"); | |
} | |
}; | |
$('.g-recaptcha').each(loadRecaptcha); // load all reCAPTCHA async | |
}; | |
// only react on resize and scroll events you might need to debounce if necessary | |
$(window).on('resize scroll', loadRecaptchaAsync); | |
// do one initial check because reCAPTCHA might be in viewport | |
loadRecaptchaAsync(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment