ask
ask

Reputation: 25

if cookie is set, embed google analytics

I want to execute something like this:

if (document.cookie.indexOf('cookie') > -1 ) {
  <script>...
  <script>
   window.dataLayer = window.dataLayer || [];
   etc.
}

and I read somewhere else that document.write is a bad way.

Thanks.

Upvotes: 0

Views: 34

Answers (1)

Justinas
Justinas

Reputation: 43451

Wrap it opposite way. Use <script> tag and then if inside:

<script>
    if (document.cookie.indexOf('cookie') > -1 ) {
        window.dataLayer = window.dataLayer || [];
        /* ... */
    }
</script>

Then if no cookie present, script simply will not initiate.


If you need some custom tag, use this code (in jQuery, but you will get the idea)

var head = $('head'); // Select <head>, or any other element that will wrap your script
var scriptTag = $('<script>', {async: 'async', src: 'http://google.com/...', /*... */}); // Create new element in head

head.prepend(scriptTag); // Put your new element to the end of <head>

But do you really need that? Try to use jQuery.getScript()

Upvotes: 1

Related Questions