Better StatCounter Code
Recently, I switched to StatCounter for my web stats. I briefly used Piwik, which seemed great until I realized all visits were being logged as a “Direct Entry” and there seemed to be nothing that could be done to fix the problem (I checked mod_cloudflare, etc. to no avail). StatCounter has everything I need and is accurate.
The values for variables such as
sc_security have been changed. If you use StatCounter, you’ll need to make sure those match the values in the default code that StatCounter provides you. I also removed the
<noscript> section since it’s not relevant to this article and added indentation for readability.
The first three lines should remain as-is; these are global variables required by StatCounter.
The fourth line, beginning with
var scJsHost ..., can be condensed to remove the ternary statement if your website is set to always redirect to HTTPS:
var scJsHost = "https://secure.";
The next thing is a
document.write line that I don’t want there. According to this Google Developers page:
One known cause of poor performance is the use of document.write() inside pages, specifically those uses that inject scripts. As innocuous as the following looks, it can cause real issues for users.
So let’s get rid of that entire line and replace it with something better:
This portion can be wrapped in a self-calling function to prevent creating any unnecessary global variables.
Here’s a line-by-line breakdown of the rest of the code:
- Create a new script tag.
- Set the tag’s
- Set the
srcURL using the previously defined
- Load the script asynchronously.
- Defer loading until the page completes.
- Append the script to the page’s
Overall, it’s not much, but it’s an improvement over the code that StatCounter provides you. I also verified that stats are still working properly after these changes.
On this website, I combine these changes with resource preloading for even better performance.