이 문서에서는 reCAPTCHA 스크립트 태그 로드에 관한 권장사항을 설명합니다. 이 정보는 reCAPTCHA v2 및 v3에 모두 적용됩니다.
비동기식으로 reCAPTCHA 로드
모든 reCAPTCHA 버전은 비동기식으로 로드될 수 있습니다. reCAPTCHA를 비동기식으로 로드해도 의심스러운 트래픽을 식별하는 기능에는 영향을 미치지 않습니다. 비동기 스크립트의 성능상 이점이 있으므로 reCAPTCHA를 비동기식으로 로드하는 것이 좋습니다.
<script async src="https://www.google.com/recaptcha/api.js">
reCAPTCHA를 비동기식으로 로드할 때는 로드가 완료될 때까지 reCAPTCHA를 사용할 수 없다는 점에 유의하세요. 예를 들어 다음 코드는 손상될 수 있습니다.
<script async src="https://www.google.com/recaptcha/api.js"></script>
<script>
// If reCAPTCHA is still loading, grecaptcha will be undefined.
grecaptcha.ready(function(){
grecaptcha.render("container", {
sitekey: "ABC-123"
});
});
</script>
상황에 따라서는 스크립트 순서를 조정해도 경합 상태를 방지할 수 있습니다. 또는 reCAPTCHA를 로드하는 페이지에 다음 코드 스니펫을 포함하여 경합 상태를 방지할 수 있습니다. grecaptcha.ready()
를 사용하여 API 호출을 래핑하는 경우 언제든지 reCAPTCHA를 호출하도록 다음 코드 스니펫을 추가하세요.
<script async src="https://www.google.com/recaptcha/api.js"></script>
<script>
// How this code snippet works:
// This logic overwrites the default behavior of `grecaptcha.ready()` to
// ensure that it can be safely called at any time. When `grecaptcha.ready()`
// is called before reCAPTCHA is loaded, the callback function that is passed
// by `grecaptcha.ready()` is enqueued for execution after reCAPTCHA is
// loaded.
if(typeof grecaptcha === 'undefined') {
grecaptcha = {};
}
grecaptcha.ready = function(cb){
if(typeof grecaptcha === 'undefined') {
// window.__grecaptcha_cfg is a global variable that stores reCAPTCHA's
// configuration. By default, any functions listed in its 'fns' property
// are automatically executed when reCAPTCHA loads.
const c = '___grecaptcha_cfg';
window[c] = window[c] || {};
(window[c]['fns'] = window[c]['fns']||[]).push(cb);
} else {
cb();
}
}
// Usage
grecaptcha.ready(function(){
grecaptcha.render("container", {
sitekey: "ABC-123"
});
});
</script>
또는 v2 API를 사용하는 사이트에서 onload
콜백을 사용하는 것이 유용할 수 있습니다. reCAPTCHA 로드가 완료되면 onload
콜백이 실행됩니다. reCAPTCHA 스크립트를 로드하기 전에 onload
콜백을 정의해야 합니다.
<script>
const onloadCallback = function() {
console.log("reCAPTCHA has loaded!");
grecaptcha.reset();
};
</script>
<script async src="https://www.google.com/recaptcha/api.js?onload=onloadCallback”></script>
reCAPTCHA를 비동기식으로 로드할 수 없는 경우 reCAPTCHA의 preconnect
리소스 힌트를 포함하는 것이 좋습니다. 이렇게 하면 스크립트 다운로드가 파서를 차단하는 시간이 최소화됩니다.
리소스 힌트 사용
문서의 <head>
에 다음 리소스 힌트를 포함하면 reCAPTCHA에서 사용되는 리소스를 전달하는 데 걸리는 시간이 줄어듭니다. preconnect
리소스 힌트는 브라우저가 서드 파티 출처와 조기에 연결하도록 지시합니다.
<link rel="preconnect" href="https://www.google.com">
<link rel="preconnect" href="https://www.gstatic.com" crossorigin>
지연 로드
일반적으로 reCAPTCHA에 관한 페이지 정보가 많을수록 사용자 작업이 합법적인지 파악할 수 있습니다. 사용자 본인 확인 요청에 의존하지 않는 reCAPTCHA 버전을 사용할 때 특히 그렇습니다. 따라서 특정한 제한된 작업 (예: 양식 제출)이 발생할 때까지 reCAPTCHA를 기다리는 것은 일반적으로 권장되지 않습니다.