当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 最小化的 Google Analytics 代码

最小化的 Google Analytics 代码

2019年01月19日  | 移动技术网IT编程  | 我要评论

一个简单的代码段,用于跟踪网站上的网页浏览量,而无需添加外部库。 也适用于使用react和vue.js等单页应用程序。

before

google tag manager + analytics = 73kb

after

snippet = 1.5kb

<script>
  (function(a,b,c){var d=a.history,e=document,f=navigator||{},g=localstorage,
  h=encodeuricomponent,i=d.pushstate,k=function(){return math.random().tostring(36)},
  l=function(){return g.cid||(g.cid=k()),g.cid},m=function(r){var s=[];for(var t in r)
  r.hasownproperty(t)&&void 0!==r[t]&&s.push(h(t)+"="+h(r[t]));return s.join("&")},
  n=function(r,s,t,u,v,w,x){var z="https://www.google-analytics.com/collect",
  a=m({v:"1",ds:"web",aip:c.anonymizeip?1:void 0,tid:b,cid:l(),t:r||"pageview",
  sd:c.colordepth&&screen.colordepth?screen.colordepth+"-bits":void 0,dr:e.referrer||
  void 0,dt:e.title,dl:e.location.origin+e.location.pathname+e.location.search,ul:c.language?
  (f.language||"").tolowercase():void 0,de:c.characterset?e.characterset:void 0,
  sr:c.screensize?(a.screen||{}).width+"x"+(a.screen||{}).height:void 0,vp:c.screensize&&
  a.visualviewport?(a.visualviewport||{}).width+"x"+(a.visualviewport||{}).height:void 0,
  ec:s||void 0,ea:t||void 0,el:u||void 0,ev:v||void 0,exd:w||void 0,exf:"undefined"!=typeof x&&
  !1==!!x?0:void 0});if(f.sendbeacon)f.sendbeacon(z,a);else{var y=new xmlhttprequest;
  y.open("post",z,!0),y.send(a)}};d.pushstate=function(r){return"function"==typeof d.onpushstate&&
  d.onpushstate({state:r}),settimeout(n,c.delay||10),i.apply(d,arguments)},n(),
  a.ma={trackevent:function o(r,s,t,u){return n("event",r,s,t,u)},
  trackexception:function q(r,s){return n("exception",null,null,null,null,r,s)}}})
  (window,"xx-xxxxxxxxx-x",{anonymizeip:true,colordepth:true,characterset:true,screensize:true,language:true});
</script>

setup: just put the snippet into your html, replace 'xx-xxxxxxxxx-x' with your tracking id and you're ready to go. you can also add options for what information you want to track.

event: ma.trackevent('category', 'action', 'label', 'value')

exception: ma.trackexception('description', 'fatal')

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网