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.

However, looking at the JavaScript code StatCounter provides to be included on my website, it could definitely use a few tweaks. Here’s what the original code looks like:

<!-- Start of StatCounter Code for Default Guide -->
<script type="text/javascript">
    var sc_project=12345678;
    var sc_invisible=1;
    var sc_security="11111111";
    var scJsHost = (("https:" == document.location.protocol) ?
        "https://secure." : "http://www.");
    document.write("<sc"+"ript type='text/javascript' src='" +
        scJsHost + "'></"+"script>");

The values for variables such as sc_project and 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:

(function() {
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = scJsHost + "";
    s.async = true;
    s.defer = true;

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:

  1. Create a new script tag.
  2. Set the tag’s type to “text/javascript”.
  3. Set the src URL using the previously defined scJsHost global.
  4. Load the script asynchronously.
  5. Defer loading until the page completes.
  6. Append the script to the page’s <body> tag.

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.

HostGator $3.96

$3.96 for web hosting – used by Get started today.