logo
post image

Measuring Site Analytics with Javascript - Page Views & Bounce Rate

These series of tutorials will explain how to measure site analytics using custom Javascript, rather than using third party analytics libraries such as Google Analytics.

This tutorial explains the implementation of page views & bounce rate.

What is a Page View ?

A page view happens when the page is loaded in the browser. A repeated view of a page — such as reloading / navigating to another page and then going back to the original page — is also counted as a page view.

Implementing Page Views Analytics in Code

To implement this idea in Javascript, we need to send an AJAX request to the server on page load.

  • We can either use DOMContentLoaded or load event to signal the page load.
  • DOMContentLoaded event is fired when browser fully loads the HTML & DOM tree is built. External resources such as images, stylesheets may or may not be loaded.
  • load event is fired when browser loads the HTML & all other external resources.
  • document.URL gives the full URL of the current page. This can be used to get the URL path & query parameters on the server side script.
  • document.title gives the title of the current page.
window.addEventListener('load', function() {
	let page_data = {
		url: document.URL,
		title: document.title
	};

	fetch('https://website.com/analytics.php', {
		method: 'POST',
		credentials: 'same-origin',
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify(data)
	});
});

To handle errors, read Javascript fetch() Error Handling.

Calculating Unique Page Views

Unique page views can be calculated on the server side by averaging page views relative to the page URL.

Implementing Page Views Along With Sessions

While sending page view data to the server, we can also send the session analytics data. The session data will help to calculate metrics like page views per session, number of sessions, sequence of pages visited in a single sesion etc.

To implement this idea in Javascript, a session id is also sent in the AJAX request along with the rest of the page data.

To know about sessions and how session ids are created as shown below, read Measuring Session Analytics with Javascript.

window.addEventListener('load', function() {
	// current timestamp in seconds
	let current_ts = Math.floor(Date.now() / 1000);

	// if session-id local storage item does not exist
	// if expiry-ts local storage item does not exist
	// if session time has expired
	if(localStorage.getItem('session-id') === null || localStorage.getItem('expiry-ts') === null || current_ts > parseInt(localStorage.getItem('expiry-ts'), 10)) {
		// create a new session with a random id and store
		// random id here is a concat of rand(11111111, 99999999) and timestamp
		let session_id = [(Math.floor(Math.random() * (99999999 - 11111111 + 1)) + 11111111), Date.now()].join('');
		localStorage.setItem('session-id', session_id);
	}

	// set expiry to current timestamp + 30 minutes
	localStorage.setItem('expiry-ts', current_ts + 1800);

	// page data to send
	let page_data = {
		url: document.URL,
		title: document.title,
		session_id: localStorage.getItem('session-id')
	};

	// send AJAX request
	fetch('https://website.com/analytics.php', {
		method: 'POST',
		credentials: 'same-origin',
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify(data)
	});
});

Calculating Number of Sessions

Number of sessions can be calculated on the server side by adding the number of unique session ids.

Calculating Page Views Per Session

Page views per session can be calculated on the server side by dividing the total page views by the total number of sessions.

Calculating Bounce Rate

What is a bounce: Bounce is a session having a single page view.

What is bounce rate: Bounce rate is the percentage of sessions having single page view. For example if there are 5 sessions in total, out of which 4 contained only single page views, the bounce rate would be 80%.

Bounce rate can be calculated by dividing single page view sessions divided by the total number of sessions.