Home > Software engineering >  How to Insert Google Analytics code with jQuery
How to Insert Google Analytics code with jQuery

Time:03-22

I'm working with a site where the previous dev has hard-coded the <head> section in 30 HTML pages. No footer either.

Is there a way I can insert the GTAG into every page via jQuery?

Any feedback is appreciated!

CodePudding user response:

In theory, you could add it through an append if there is a single JavaScript file that links to all other pages. Do keep in mind that the example provided has not been tested through GA and it's also not a safe way to do it considering that your source code will be viewable by any person. I hope it helps, best of luck! :)

$(document).ready(function() {
    console.log("working");
    
    let gtag = `
        <script async src="https://www.googletagmanager.com/gtag/js?id=///"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){
                dataLayer.push(arguments);
            }
            gtag('js', new Date());
            gtag('config', '///');
        </script>
    `;
    console.log(gtag);
    
    $("head").append(gtag);
});
  • Related