With JavaScript we can insert those scripts that generate third-party cookies only when users have consented to their use.

We can use an empty script element in the head section that we're going to dynamically populate with the JavaScript embed code.

    <script id="ga"></script>

'use strict';

// https://developers.google.com/analytics/devguides/collection/analyticsjs

const insertGA = target => {
    if(target === null || !target) {
        return false;
    const gaScript = `(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

                        ga('create', 'UA-XXXXX-Y', 'auto');
                        ga('send', 'pageview');`;
    target.textContent = gaScript;

An example:

document.querySelector('#accept-cookies').addEventListener('click', e => {
}, false);

By using the textContent property, a browser is now able to make the embed code run.