GDPR & AdSense: How to Create a Cookie Consent Modal that Defers Ads from Loading

Here you can find the code to accompany my video on blocking AdSense scripts from loading until the user has given consent:

Here’s the HTML code for the consent modal:

<div id="consentModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="false" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<h2 class="text-center">Trust and transparency is important to us.</h2>
<p class="text-justify">
It takes a lot of work to build, maintain, and improve a free online tool like this. We and third parties use tech like cookies to make this happen.
</p>
<p class="text-justify">
By continuing, you consent to the use of these technologies, and affirm you're at least 16 years old or have consent from a parent or guardian.
</p>
<button id="giveCookieConsentButton" class="btn btn-primary btn-lg center-block" data-dismiss="modal" aria-hidden="false"> OK. Let's go! </button>
</div>
</div>
</div>
</div>

And here goes the Javascript code that will block the AdSense script and ads from loading:

// cookie methods are taken from https://stackoverflow.com/questions/1458724/how-do-i-set-unset-a-cookie-with-jquery
function setCookie(key, value) {
    var expires = new Date();
    expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
    document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}

function getCookie(key) {
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
}

function handleCookieConsentGiven(key) {
    setCookie("consentgiven2513834176315", true);

    // load adsense script
    var script = document.createElement('script');
    script.src = "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
    document.head.appendChild(script);
    (adsbygoogle = window.adsbygoogle || []).push({
      google_ad_client: "ca-pub-9441750949528332",
      enable_page_level_ads: true
    });
}

$(document).ready( function() {
    if (!getCookie("consentgiven2513834176315")) {
        $('#consentModal').modal('show');
    }
    else {
        handleCookieConsentGiven();
    }
    document.getElementById("giveCookieConsentButton").addEventListener("click", handleCookieConsentGiven);
});

You will use your AdSense ad units as usual, placing the code that AdSense provides you within your HTML. Deferring the loading of the main script will prevent the ad unit from initialising.