Skip to content

Commit 5466c0e

Browse files
committed
Refactor: Move GoatCounter initialization to main.js module and reformat count.js.
1 parent 62b58e4 commit 5466c0e

File tree

3 files changed

+294
-361
lines changed

3 files changed

+294
-361
lines changed

docs/count.js

Lines changed: 48 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,40 @@
1-
// GoatCounter: https://www.goatcounter.com
2-
// This file is released under the ISC license: https://opensource.org/licenses/ISC
3-
;(function() {
1+
; (function () {
42
'use strict';
5-
63
window.goatcounter = window.goatcounter || {}
7-
8-
// Load settings from data-goatcounter-settings.
94
var s = document.querySelector('script[data-goatcounter]')
105
if (s && s.dataset.goatcounterSettings) {
11-
try { var set = JSON.parse(s.dataset.goatcounterSettings) }
6+
try { var set = JSON.parse(s.dataset.goatcounterSettings) }
127
catch (err) { console.error('invalid JSON in data-goatcounter-settings: ' + err) }
138
for (var k in set)
149
if (['no_onload', 'no_events', 'allow_local', 'allow_frame', 'path', 'title', 'referrer', 'event'].indexOf(k) > -1)
1510
window.goatcounter[k] = set[k]
1611
}
17-
1812
var enc = encodeURIComponent
19-
20-
// Get all data we're going to send off to the counter endpoint.
21-
window.goatcounter.get_data = function(vars) {
13+
window.goatcounter.get_data = function (vars) {
2214
vars = vars || {}
2315
var data = {
24-
p: (vars.path === undefined ? goatcounter.path : vars.path),
16+
p: (vars.path === undefined ? goatcounter.path : vars.path),
2517
r: (vars.referrer === undefined ? goatcounter.referrer : vars.referrer),
26-
t: (vars.title === undefined ? goatcounter.title : vars.title),
18+
t: (vars.title === undefined ? goatcounter.title : vars.title),
2719
e: !!(vars.event || goatcounter.event),
2820
s: window.screen.width,
2921
b: is_bot(),
3022
q: location.search,
3123
}
32-
33-
var rcb, pcb, tcb // Save callbacks to apply later.
34-
if (typeof(data.r) === 'function') rcb = data.r
35-
if (typeof(data.t) === 'function') tcb = data.t
36-
if (typeof(data.p) === 'function') pcb = data.p
37-
24+
var rcb, pcb, tcb
25+
if (typeof (data.r) === 'function') rcb = data.r
26+
if (typeof (data.t) === 'function') tcb = data.t
27+
if (typeof (data.p) === 'function') pcb = data.p
3828
if (is_empty(data.r)) data.r = document.referrer
3929
if (is_empty(data.t)) data.t = document.title
4030
if (is_empty(data.p)) data.p = get_path()
41-
4231
if (rcb) data.r = rcb(data.r)
4332
if (tcb) data.t = tcb(data.t)
4433
if (pcb) data.p = pcb(data.p)
4534
return data
4635
}
47-
48-
// Check if a value is "empty" for the purpose of get_data().
49-
var is_empty = function(v) { return v === null || v === undefined || typeof(v) === 'function' }
50-
51-
// See if this looks like a bot; there is some additional filtering on the
52-
// backend, but these properties can't be fetched from there.
53-
var is_bot = function() {
54-
// Headless browsers are probably a bot.
36+
var is_empty = function (v) { return v === null || v === undefined || typeof (v) === 'function' }
37+
var is_bot = function () {
5538
var w = window, d = document
5639
if (w.callPhantom || w._phantom || w.phantom)
5740
return 150
@@ -63,51 +46,39 @@
6346
return 153
6447
return 0
6548
}
66-
67-
// Object to urlencoded string, starting with a ?.
68-
var urlencode = function(obj) {
49+
var urlencode = function (obj) {
6950
var p = []
7051
for (var k in obj)
7152
if (obj[k] !== '' && obj[k] !== null && obj[k] !== undefined && obj[k] !== false)
7253
p.push(enc(k) + '=' + enc(obj[k]))
7354
return '?' + p.join('&')
7455
}
75-
76-
// Show a warning in the console.
77-
var warn = function(msg) {
56+
var warn = function (msg) {
7857
if (console && 'warn' in console)
7958
console.warn('goatcounter: ' + msg)
8059
}
81-
82-
// Get the endpoint to send requests to.
83-
var get_endpoint = function() {
60+
var get_endpoint = function () {
8461
var s = document.querySelector('script[data-goatcounter]')
8562
return (s && s.dataset.goatcounter) ? s.dataset.goatcounter : goatcounter.endpoint
8663
}
87-
88-
// Get current path.
89-
var get_path = function() {
64+
var get_path = function () {
9065
var loc = location,
9166
c = document.querySelector('link[rel="canonical"][href]')
92-
if (c) { // May be relative or point to different domain.
67+
if (c) {
9368
var a = document.createElement('a')
9469
a.href = c.href
9570
if (a.hostname.replace(/^www\./, '') === location.hostname.replace(/^www\./, ''))
9671
loc = a
9772
}
9873
return (loc.pathname + loc.search) || '/'
9974
}
100-
101-
// Run function after DOM is loaded.
102-
var on_load = function(f) {
75+
var on_load = function (f) {
10376
if (document.body === null)
104-
document.addEventListener('DOMContentLoaded', function() { f() }, false)
77+
document.addEventListener('DOMContentLoaded', function () { f() }, false)
10578
else
10679
f()
10780
}
108-
109-
// Filter some requests that we (probably) don't want to count.
110-
window.goatcounter.filter = function() {
81+
window.goatcounter.filter = function () {
11182
if ('visibilityState' in document && document.visibilityState === 'prerender')
11283
return 'visibilityState'
11384
if (!goatcounter.allow_frame && location !== parent.location)
@@ -120,119 +91,94 @@
12091
return 'disabled with #toggle-goatcounter'
12192
return false
12293
}
123-
124-
// Get URL to send to GoatCounter.
125-
window.goatcounter.url = function(vars) {
94+
window.goatcounter.url = function (vars) {
12695
var data = window.goatcounter.get_data(vars || {})
127-
if (data.p === null) // null from user callback.
96+
if (data.p === null)
12897
return
129-
data.rnd = Math.random().toString(36).substr(2, 5) // Browsers don't always listen to Cache-Control.
130-
98+
data.rnd = Math.random().toString(36).substr(2, 5)
13199
var endpoint = get_endpoint()
132100
if (!endpoint)
133101
return warn('no endpoint found')
134-
135102
return endpoint + urlencode(data)
136103
}
137-
138-
// Count a hit.
139-
window.goatcounter.count = function(vars) {
104+
window.goatcounter.count = function (vars) {
140105
var f = goatcounter.filter()
141106
if (f)
142107
return warn('not counting because of: ' + f)
143108
var url = goatcounter.url(vars)
144109
if (!url)
145110
return warn('not counting because path callback returned null')
146-
147111
if (!navigator.sendBeacon(url)) {
148-
// This mostly fails due to being blocked by CSP; try again with an
149-
// image-based fallback.
150112
var img = document.createElement('img')
151113
img.src = url
152-
img.style.position = 'absolute' // Affect layout less.
114+
img.style.position = 'absolute'
153115
img.style.bottom = '0px'
154116
img.style.width = '1px'
155117
img.style.height = '1px'
156118
img.loading = 'eager'
157119
img.setAttribute('alt', '')
158120
img.setAttribute('aria-hidden', 'true')
159-
160-
var rm = function() { if (img && img.parentNode) img.parentNode.removeChild(img) }
121+
var rm = function () { if (img && img.parentNode) img.parentNode.removeChild(img) }
161122
img.addEventListener('load', rm, false)
162123
document.body.appendChild(img)
163124
}
164125
}
165-
166-
// Get a query parameter.
167-
window.goatcounter.get_query = function(name) {
126+
window.goatcounter.get_query = function (name) {
168127
var s = location.search.substr(1).split('&')
169128
for (var i = 0; i < s.length; i++)
170129
if (s[i].toLowerCase().indexOf(name.toLowerCase() + '=') === 0)
171130
return s[i].substr(name.length + 1)
172131
}
173-
174-
// Track click events.
175-
window.goatcounter.bind_events = function() {
176-
if (!document.querySelectorAll) // Just in case someone uses an ancient browser.
132+
window.goatcounter.bind_events = function () {
133+
if (!document.querySelectorAll)
177134
return
178-
179-
var send = function(elem) {
180-
return function() {
135+
var send = function (elem) {
136+
return function () {
181137
goatcounter.count({
182-
event: true,
183-
path: (elem.dataset.goatcounterClick || elem.name || elem.id || ''),
184-
title: (elem.dataset.goatcounterTitle || elem.title || (elem.innerHTML || '').substr(0, 200) || ''),
138+
event: true,
139+
path: (elem.dataset.goatcounterClick || elem.name || elem.id || ''),
140+
title: (elem.dataset.goatcounterTitle || elem.title || (elem.innerHTML || '').substr(0, 200) || ''),
185141
referrer: (elem.dataset.goatcounterReferrer || elem.dataset.goatcounterReferral || ''),
186142
})
187143
}
188144
}
189-
190-
Array.prototype.slice.call(document.querySelectorAll("*[data-goatcounter-click]")).forEach(function(elem) {
145+
Array.prototype.slice.call(document.querySelectorAll("*[data-goatcounter-click]")).forEach(function (elem) {
191146
if (elem.dataset.goatcounterBound)
192147
return
193148
var f = send(elem)
194149
elem.addEventListener('click', f, false)
195-
elem.addEventListener('auxclick', f, false) // Middle click.
150+
elem.addEventListener('auxclick', f, false)
196151
elem.dataset.goatcounterBound = 'true'
197152
})
198153
}
199-
200-
// Add a "visitor counter" frame or image.
201-
window.goatcounter.visit_count = function(opt) {
202-
on_load(function() {
203-
opt = opt || {}
204-
opt.type = opt.type || 'html'
154+
window.goatcounter.visit_count = function (opt) {
155+
on_load(function () {
156+
opt = opt || {}
157+
opt.type = opt.type || 'html'
205158
opt.append = opt.append || 'body'
206-
opt.path = opt.path || get_path()
207-
opt.attr = opt.attr || {width: '200', height: (opt.no_branding ? '60' : '80')}
208-
159+
opt.path = opt.path || get_path()
160+
opt.attr = opt.attr || { width: '200', height: (opt.no_branding ? '60' : '80') }
209161
opt.attr['src'] = get_endpoint() + 'er/' + enc(opt.path) + '.' + enc(opt.type) + '?'
210162
if (opt.no_branding) opt.attr['src'] += '&no_branding=1'
211-
if (opt.style) opt.attr['src'] += '&style=' + enc(opt.style)
212-
if (opt.start) opt.attr['src'] += '&start=' + enc(opt.start)
213-
if (opt.end) opt.attr['src'] += '&end=' + enc(opt.end)
214-
215-
var tag = {png: 'img', svg: 'img', html: 'iframe'}[opt.type]
163+
if (opt.style) opt.attr['src'] += '&style=' + enc(opt.style)
164+
if (opt.start) opt.attr['src'] += '&start=' + enc(opt.start)
165+
if (opt.end) opt.attr['src'] += '&end=' + enc(opt.end)
166+
var tag = { png: 'img', svg: 'img', html: 'iframe' }[opt.type]
216167
if (!tag)
217168
return warn('visit_count: unknown type: ' + opt.type)
218-
219169
if (opt.type === 'html') {
220170
opt.attr['frameborder'] = '0'
221-
opt.attr['scrolling'] = 'no'
171+
opt.attr['scrolling'] = 'no'
222172
}
223-
224173
var d = document.createElement(tag)
225174
for (var k in opt.attr)
226175
d.setAttribute(k, opt.attr[k])
227-
228176
var p = document.querySelector(opt.append)
229177
if (!p)
230178
return warn('visit_count: element to append to not found: ' + opt.append)
231179
p.appendChild(d)
232180
})
233181
}
234-
235-
// Make it easy to skip your own views.
236182
if (location.hash === '#toggle-goatcounter') {
237183
if (localStorage.getItem('skipgc') === 't') {
238184
localStorage.removeItem('skipgc', 't')
@@ -243,24 +189,19 @@
243189
alert('GoatCounter tracking is now DISABLED in this browser until ' + location + ' is loaded again.')
244190
}
245191
}
246-
247192
if (!goatcounter.no_onload)
248-
on_load(function() {
249-
// 1. Page is visible, count request.
250-
// 2. Page is not yet visible; wait until it switches to 'visible' and count.
251-
// See #487
193+
on_load(function () {
252194
if (!('visibilityState' in document) || document.visibilityState === 'visible')
253195
goatcounter.count()
254196
else {
255-
var f = function(e) {
197+
var f = function (e) {
256198
if (document.visibilityState !== 'visible')
257199
return
258200
document.removeEventListener('visibilitychange', f)
259201
goatcounter.count()
260202
}
261203
document.addEventListener('visibilitychange', f)
262204
}
263-
264205
if (!goatcounter.no_events)
265206
goatcounter.bind_events()
266207
})

0 commit comments

Comments
 (0)