Search code examples
javascripthtmlgoogle-analyticshead

Placing Google Analytics in a separate file


I have a bunch of static webpages that used to have GA code placed before </body> tag. I was tasked to place them before the </head> tag (as recommended by Google). (Personally, I think this is a silly request but you have to make the client happy.)

Now, my question is not about the benefit of having GA code in the <body> opposed to the <head> but about whether placing the GA code in a script file (that is in the <head> tag) would be the same as placing it inline right before </head> tag?

For example,

index.html

 <head>
     <!-- some stylesheet files -->
     <!-- some script files -->
     <script>
         // Google Analytics code
     </script>
 </head>

versus

index.html

 <head>
     <!-- some stylesheet files -->
     <!-- some script files -->
     <script src="main.js"></script>
     <!-- some more script files -->
 </head>

main.js

 // random JS code followed by Google Analytics code

Solution

  • You can place the GA code inside your main.js then you'll not have to explicitly place the GA code on all pages.