https://developers.google.com/analytics/devguides/collection/analyticsjs
Add analytics.js to Your Site | Analytics for Web (analytics.js)
A JavaScript library that lets you measure how users interact with your website.
developers.google.com
1. Site에 analytics.js include 하기
1) Google Analytics tag는 head상단, 다른 스크립트나 CSS태그보다 먼저 import되어야 한다.
2) GA_MEASUREMENT_ID는 내가 사용하는 propertyID로 대체해야 한다.
GA 태그
<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
코드 설명
- https://www.google-analytics.com/analytics.js 에서 비동기방식으로 다운로드 하한다.
- GA함수를 초기화한다. analytics.js라이브러리가 로딩 후 실행준비가 완료되면 명령어를 예약할 수 있다.
- GA()호출을 통해 GA_MEASUREMENT_ID 매개변수를 통해 tracker object를 생성하도록 대기열에 명령어를 추가 할 수있다
- GA()호출을 통해 현재 페이지의 페이지뷰를 GA로 보내도록 대기열에 명령을 추가 할 수 있다.
- 위의 예제에서 마지막 2줄은 필요에 따라 수정할 수 있지만 analytics.js를 로딩하는 코드나 ga command queue 함수를 초기화하는 부분은 수정하면 안된다.
GA가 처리 할 수 있는 데이터의 종류
사용자가 방문하는 각각의 페이지에 pageview를 전달해야한다.
- 사이트에서 보낸 총 시간
- 각각의 페이지에서 보낸 시간 / 어떤 순서로 페이지를 방문했는지
cracker object가 생성될때 IP Address, userAgent등을 수집하는데, analytics.js는 아래와 같은 항목을 결정 하는데 사용된다.
- 사용자의 위치
- 사용자가 사용하는 브라우저나 운영체제
- 스크린 사이즈
- 리퍼러
2. analytics.js 동작 원리
*CREATE / SET / SEND Command를 기억하자*
GA Command Queue
- 위에서 선언한 GA태그는 Command Quere라고 알려진 ga전역함수를 선언한다.
- Command Queue라고 이름붙여진 이유는, command를 받은 즉시 실행하는것이 아니라, analytics.js라이브러리가 완전히 로드될때까지 command를 Queue에 추가하기 때문이다.
- GA는 q라는 빈 배열 Propertie를 선언하는데, analytics.js라이브러리가 로드되기전에 ga함수를 호출하면 ga함수에 전달된 인수들이 q배열의 끝에 추가된다.
- 예를들자면 GA 태그 코드 실행 직후 GA의 q를 콘솔로 찍어보면, 실제로 Command가 출력되는것을 확인 할 수 있다.
console.log(ga.q);
// Outputs the following:
// [
// ['create', 'UA-XXXXX-Y', 'auto'],
// ['send', 'pageview']
// ]
- analytics.js 라이브러리가 로딩되면, ga.q 배열을 검사하다 순서대로 command를 실행한다.
그런다음 ga함수가 재정의되므로, 모든 후속 호출이 즉시 실행된다.
- 이런 방식은 analytics.js의 로딩 여부와 상관없이, ga Command Quere를 사용하도록 해준다
- 복잡한 비동기 코드의 대부분을 추상화하는 간단한 동기식 인터페이스를 제공한다.
queue에 Command 추가하기
- Command queue에 대한 모든 호출은 공통적인 규칙을 가진다.
ga(${COMMAND}, ${arguments}...)
// command : analytics.js의 메서드를 식별하는 문자열
// 나머지는 그 메서드로 전달되는 인수들이다.
- Command를 참조하는 방법은 ga.create같은 전역메서드거나, send같은 Tracker Object를 참조하는 방법일 수 있다.
- GA는 모르는 command가 들어오면 무시하므로 안전하다.
- GA Command 참고 www.developers.google.com/analytics/devguides/collection/analyticsjs/command-queue-reference
Command Parameters
- 편의를 위해 analytics.js Commands들은 다양한 형식의 매개변수를 받을 수 있다.
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
//Object로도 보낼 수 있다.
ga('create', {
trackingId: 'UA-XXXXX-Y',
cookieDomain: 'auto'
});
ga('send', {
hitType: 'pageview'
});
create : trackingId / cookieDomain을 받는다.
send : hitType을 받는다.
3. Trackers 생성
Trackers란
- Tracker Object(trackers)는 데이터를 수집하고 저장해서 GA에 전달 할 수 있는 오브젝트이다.
- 새로운 Tracker를 생성하기 위해서는 Tracking ID가 반드시 필요하다. (UA-XXXX-Y)
- Cookie Domain 설정도 지정이 필요한데 auto로 설정하면 자동으로 Cookie 도메인이 설정된다.
예를들어, 주소가 blog.example.co.uk 라면 쿠키 도메인은 .example.co.uk로설정된다.
만약 local에서 서버를 돌리면(localhost) cookieDomain은 none으로 설정된다.
Naming trackers
//4번째 인자로 Tracker의 이름을 지정 할 수 있다.
ga('create', 'UA-XXXXX-Y', 'auto', 'myTracker');
tracker에 이름이 필요한 경우는 동일한 페이지에 두개 이상의 tracker를 생성할때이다.
name field를 지정해주지 않으면 default 트래커가 생성되고, Default Tracker의 내부 이름은 t0이다.
Specifying fields at creation time
ga('create', 'UA-XXXXX-Y', 'auto', 'myTracker', {
userId: '12345'
});
- optional field에 object를 전달해서 traker에 저장되고 전송될때마다 적용될수 있다(??)
+ 여러개의 Tracker를 사용 할 경우에는
https://developers.google.com/analytics/devguides/collection/analyticsjs/creating-trackers
링크의 Running commands for a specific tracker를 참고한다.
4. Tracker Data 설정 및 가져오기
- Tracker에서 필드 데이터를 set하고 get하려면 때때로 Tracker자체의 참조가 필요하다.
Commands가 GA Command Queue에 추가되고 비동기적으로 실행되고 return값을 반환하지 않기때문에
- Tracker는 일반적으로 Create Command에 의해 생성되므로, Tracker Object의 참조를 get하기 위해서는 Create Command가 실행될때까지 기다려야 한다. 콜백을 통해 작업을 수행 할 수 있다.
The ready callback
ready callback은 ga Command Queue에 추기 할 수 있는 함수다. 이 함수는 analytics.js 라이브러리가 모두 로드되될 때 호출된다. 그리고 큐에 추가된 모든 이전 Command들은 실행된다.
- 모든 Command들은 순서대로 실행되기 때문에, create command 를 추가한 다음에 ready callback을 큐에 추가하는것은 tracker가 생성된 후에 ready callback이 실행되도록 한다. (순서를 보장시켜준다는 의미다.)
//1) Create Tacker를 Command Queue에 추가
ga('create', 'UA-XXXXX-Y', 'auto');
//2) Ready Callback을 Command Queue에 추가
ga(function(tracker) {
// Logs the tracker created above to the console.
console.log(tracker);
});
Getting data stored on a tracker
ga('create', 'UA-XXXXX-Y', 'auto');
ga(function(tracker) {
// Logs the trackers name.
// (Note: default trackers are given the name "t0")
console.log(tracker.get('name'));
// Logs the client ID for the current user.
console.log(tracker.get('clientId'));
// Logs the URL of the referring site (if available).
console.log(tracker.get('referrer'));
});
- 한번 Tracker Object를 콜백 안에서 참조하도록 해놓는다면, TrackerObjct의 get Method를 통해 최근 Tracker에 저장된 필드의 값들을 접근 할 수 있다.
Update data
- Tracker Object는 Set Method를 사용하여 업데이트 할 수 있다.
- Tracker의 Set Method는 Tracker Obejct의 자기자신에서 호출되거나, 'set' Command에 의해 GA Command Queue에 추가함으로써 업데이트 할 수 있다.
(1) Tracker Object 업데이트 하는법 - The ga() command queue
// page Field를 about으로 설정하기
/* Default Tracker에 설정 */
ga('set', 'page', '/about');
ga('set', {
page: '/about',
title: 'About Us'
});
/*named Tracker에 설정*/
ga('myTracker.set', 'page', '/about');
(2) Tracker Object 업데이트 하는법 - On the tracker object itself
ga(function(tracker) {
tracker.set('page', '/about');
});
5. Gogle Analytics로 데이터 전송하기
Hits, hit types, and the Measurement Protocol
hit: tracker가 GA로 데이터를 전송할때 이를 hit이라고 한다. 모든 hit은 유형을 가지고 있다.
hit은 field와 value쌍으로 이루어진 인코딩된 query String이다. (HTTP request이다.)
Network Tab에서 google-analytics.com/collect로 나가는 request를 살펴보면 hit를 볼 수 있다.
hit의 종류
- pageview
- screenview
- event
- transaction
- item
- social
- exception
- timing
전송되는 데이터
tracker는 최근에 저장된 필드를 전부 전송합니다. cookieDomain이나 hitCallback을 제외하고는
event hit의 field는 eventAction과 eventLabel이다.
Knowing when the hit has been sent
몇몇 경우 GA로 hit이 전송되는 시점을 알아야 즉시 조치를 취할 수 있다. 몇몇 브라우저는 페이지가 unload될때 js코드 실행을 멈춘다. 이로인해 hit을 전송하는 명령어가 실행되지 않는다.
예를들어 form의 submit 버튼을 유저가 클릭했을때 이벤트를 발생시켜 GA로 보내고자 할때 대부분의 케이스에서 submit버튼은 다음페이지를 로딩하고 어떠한 GA send 이벤트도 실행되지 않는다.
=> 이번에 가장 헤맸었던 케이스. 페이지 이동이 일어날때, 그 다음에 실행되는 js코드는 어떻게 되는건지 궁금했었다.
이문제의 해결방법은 이벤트를 가로채서 페이지 언로드를 중지하는것이다. 그런 다음 평소와 같이 hit를 GA로 보내며 hit이 전송되면 resubmit 하게 한다.
hitCallback
hit 전송이 완료되는시점을 알기위해 hitCallback 필드를 설정할 수 있다. hitCallback은 hit이 전송되자마자 호출되는 함수이다.
// Gets a reference to the form element, assuming
// it contains the id attribute "signup-form".
var form = document.getElementById('signup-form');
// Adds a listener for the "submit" event.
form.addEventListener('submit', function(event) {
// Prevents the browser from submitting the form
// and thus unloading the current page.
event.preventDefault();
// Sends the event to Google Analytics and
// resubmits the form once the hit is done.
ga('send', 'event', 'Signup Form', 'submit', {
hitCallback: function() {
form.submit();
}
});
});
Handling timeouts
하지만 callback은 hit 전송을 성공해야 실행된다.. 위의 코드의 가장 큰 문제점은.. GA로 전송을 실패하면 메인 로직이 실행되지 않는다는것! (GA때문에 주문로직에 오류가 생긴다고 상상해보자.. 모든 원망을 다들을듯.)
따라서 analytics.js라이브러리가 로드에 실패했을경우를 제어하기 위해 반드시! timeout 함수를 사용해야한다.
// Gets a reference to the form element, assuming
// it contains the id attribute "signup-form".
var form = document.getElementById('signup-form');
// Adds a listener for the "submit" event.
form.addEventListener('submit', function(event) {
// Prevents the browser from submitting the form
// and thus unloading the current page.
event.preventDefault();
// Creates a timeout to call `submitForm` after one second.
setTimeout(submitForm, 1000);
// Keeps track of whether or not the form has been submitted.
// This prevents the form from being submitted twice in cases
// where `hitCallback` fires normally.
var formSubmitted = false;
function submitForm() {
if (!formSubmitted) {
formSubmitted = true;
form.submit();
}
}
// Sends the event to Google Analytics and
// resubmits the form once the hit is done.
ga('send', 'event', 'Signup Form', 'submit', {
hitCallback: submitForm
});
});
/* 위의 방법을 utiliy funciton으로 선언해서 사용하기 */
function createFunctionWithTimeout(callback, opt_timeout) {
var called = false;
function fn() {
if (!called) {
called = true;
callback();
}
}
setTimeout(fn, opt_timeout || 1000);
return fn;
}
// Gets a reference to the form element, assuming
// it contains the id attribute "signup-form".
var form = document.getElementById('signup-form');
// Adds a listener for the "submit" event.
form.addEventListener('submit', function(event) {
// Prevents the browser from submitting the form
// and thus unloading the current page.
event.preventDefault();
// Sends the event to Google Analytics and
// resubmits the form once the hit is done.
ga('send', 'event', 'Signup Form', 'submit', {
hitCallback: createFunctionWithTimeout(function() {
form.submit();
})
});
});
==> 잘 모르겠다. 이렇게까지 해서 hit을 전송하는것에 대해 정합성을 가져야 하는지 의문이 든다. 어쨌던 GA에 전송을 실패하면 1초후에 submit이 이루어진다는건데... 1초의 딜레이는 생각보다 영향도가 큰것같은데, 차라리 GA로 전송을 성공하건 말건 기본 로직은 동작을 해야하는것이 아닐까..?
'Today I learned' 카테고리의 다른 글
[마케팅 솔루션] AIQUA개발 관련 문서 정리 (2) - AVAILABLE FEATURES (0) | 2020.05.22 |
---|---|
[마케팅 솔루션] AIQUA개발 관련 문서 정리 (1) (0) | 2020.05.21 |
2020 읽은책 읽고있는책 읽고싶은책 정리 (0) | 2020.04.30 |
마지막주 SPA 웹사이트 만들기 튜토리얼 (0) | 2020.02.08 |
[react] 마지막주 React로 간단한 프로젝트를 진행해보자. (0) | 2020.02.08 |
댓글