Lightweight Google Analytics
This article is automatically translated by LLM, so the translation may be inaccurate or incomplete. If you find any mistake, please let me know.
You can find the original article here .
Google Analytics is a well-known web data analysis tool, and it's very easy to integrate into a webpage by simply adding a few <script>
tags to the HTML. However, for those who use some monitoring tools on their websites, they might find that it is actually a performance killer, mainly because its cache time in the headers is very short, and the script size is quite large.
Because of this, I had previously considered whether to include Google Analytics on this website. On one hand, I wanted to know which articles visitors mainly browse, but on the other hand, I didn't want to make the website too bulky and slow. After some research, I found that Google Analytics provides an API that allows users to send statistical data without needing the official script to function.
Sending Information with Measurement Protocol
Measurement Protocol is an API provided by Google Analytics that allows users to manually send some statistical data.
The method is to send a POST
(recommended) or GET
request to https://www.google-analytics.com/collect
.
For example, the following is the code for this webpage to send information to Google Analytics:
var uid = localStorage.getItem('uid') || (Math.random() + '.' + Math.random())
localStorage.setItem('uid', uid)
$.post('https://www.google-analytics.com/collect', {
v: 1,
tid: 'UA-xxxxxxxxx-x',
cid: uid,
t: 'pageview',
dp: encodeURIComponent(location.pathname)
})
The parameters inside are:
v
: The version number of the API protocol, currently only1
is available.tid
: TheUA-xxxxxxxxx-x
number used when generally using GA.cid
: A unique ID used to identify the user.t
: The type of information, such aspageview
which refers to a webpage view. All types can be referenced here.dp
: Refers to the path part of the URL, excluding the hostname and query string.
These parameters can be modified according to your needs and the Parameter Reference. I only use these parameters because I only need to know this information.
About Ad Blockers
Some people might wonder if this will be blocked by ad blockers. The answer is definitely yes, because the target for sending information is www.google-analytics.com
, so this will be blocked by most ad blockers.
Of course, some might think of setting up a reverse proxy on their own server, changing the /collect
URL to their server, and then adding the real IP to the uip
parameter before sending it to the GA server. In theory, this should be feasible (I haven't tried it), but I believe there's no need to forcibly collect data from people who don't want their data collected.