how not to trigger site analytics from localhost
I've been learning about this whole family of "web technologies" now that it looks like they're here
to stay.
It turns out javascript supports this niche concept of both if
and else
.
function addAnalytics() {
if (window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1') {
// Create a script tag for your analytics js
var analyticScript = document.createElement('script');
gtagScript.async = true;
gtagScript.src = 'https://example.com/analytics.js';
// Append the gtag.js script to the
document.body.appendChild(gtagScript);
} else {
console.log('Analytics is not loaded in local environment.');
}
}
There's a thousand other ways to write this, yeah, but the simple way of achieving the goal really made me happy.