0

The javascript part of my html files looks like that :

<script async src="myscript.js"></script>
<script async src="//www.googletagmanager.com/gtag/js?id=UA-XXXXXX-X"></script>
<script>window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('js',new Date());gtag('config','UA-XXXXXX-X');</script>

I'm not really a javascript specialist. So, I don't really understand what the last script is doing. And I wonder if I could copy and paste this code into my myscript.js to save a few bytes?

What bother me is the "async" property of my script. Is it compulsory to execute this part of the google analytics script in the beginning of the page?

I've read a lot of questions and answers about this subject but none allow me to understand clearly. And most of them are about the previous analytics script and not this one.

1 Answer 1

1
// Checks if window.dataLayer already defined. If defined, use that array else creates an empty array.
window.dataLayer=window.dataLayer||[];
//This functions add elements to the above defined array. This array is used by the google analytics script defined at the top.
//arguments is a javascript keyword to fetch all arguments passed to a function as an array.
function gtag(){
 dataLayer.push(arguments);
}
//gtag called with arguments ['js', <current date>]
gtag('js',new Date());
//gtag called with arguments ['config', <token>]
gtag('config','UA-XXXXXX-X');

end result would be:

datalayer=[
['js', <current date>],
['config', <token>]
]

Your datalayer should be defined before gtag script invocation, if not it may not work. This link explains it very well link1 and link2. So keeping datalayer in your async script will not be reliable, as its not guaranteed that your script will execute before gtag script.

2
  • Ok, nice explanation! Thanks. But can I put it in my async script?
    – Xetolone
    Commented May 6, 2018 at 7:46
  • Your datalayer should be placed/defined above the gtag script, if not it will not work. This link explains it very well link and link. So keeping datalayer in your async script will not be reliable, as its not guaranteed that your script will execute before gtag script.
    – Achu
    Commented May 6, 2018 at 13:47

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.