How to include Google Analytics in an RMarkdown generated GitHub Page?

后端 未结 2 1270
星月不相逢
星月不相逢 2021-01-02 01:35

How can I always include the Google Analytics tacking code on my GitHub Pages webpage generated with R Markdown?

I am currently creating a webpage hosted on GitHub P

相关标签:
2条回答
  • 2021-01-02 01:51

    I just figured out how to get this done while trying to add google analytics to my own RMD site on Github Pages.

    To add Google Analytics code before the closing </head> tag of an html document produced from RMD...

    Step 1: Create a .html file containing the Google Analytics Script, and save it in the working directory for your site. (Simply, create new text file, paste script, save "filename.html".

    Step 2: Adjust the yaml header of your rmd file to contain the includes: & in_header: arguments, and reference the .html file containing the tracking code

    ---
    title: ""
    output: 
      html_document:
        includes:
           in_header: GA_Script.html
    ---
    

    Step 3: Render the website knitr::render_site() to use the yaml header, so that each page reports back to Google Analytics.


    It is recommended that the Google Analytics tracking code be placed before the closing <\head> tag in the sites html. The method above will get that done.

    If for some reason you want to include it in the body of the html code, you could just include the GA code in the body of the rmd file by pasting it in between an html_preserve command:

    <!--html_preserve-->
    
    Google Analytics Code Here
    
    <!--/html_preserve-->
    
    0 讨论(0)
  • 2021-01-02 02:14

    I manually write the header in the same RMarkdown file and simply include the Google Analytics chunk. This header goes immediately after the yaml. Works like a charm.

    ---
    title: "XXXXXXXXXX"
    author: "XXXXXXXXXXX"
    date: "`r Sys.Date()`"
    ---
    
    <head>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=XXXXXXX"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'XXXXXXXXXX');
    </script>
    </head> 
    
    0 讨论(0)
提交回复
热议问题