Skip to content

Instantly share code, notes, and snippets.

@thexmanxyz
Last active March 30, 2020 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thexmanxyz/541c4f4040fa327ce0eb7d18ec861b47 to your computer and use it in GitHub Desktop.
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
// 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