Client-side conditional load of JavaScript file

last updated August 19, 2021 17:24 UTC

With AdSense introducing the latest improvement to their code, there are unwanted consequences.

In this new approach, the client identification is sent to Google much earlier. As a result, we saw inflated AdSense page view counts. It seems it is also counting pages with no Ad requests. As long as the async script load tag is there – the AdSense adds a page view. This behaviour is different from what happens with Google Analytics.

The solution in our case is to introduce server-side (easy in PHP) and, in some exceptional cases, a client-side conditional script load. This way, we can omit the script tag call for all scenarios we need.

An example of the client-side script:

var condLoad = function(src, callbackfn) {
  var AdSense = document.createElement("script");
  AdSense.type = "text/javascript";
  AdSense.setAttribute("crossorigin", "anonymous");
  AdSense.setAttribute("async", "true");
  AdSense.setAttribute("src", src);
  if (AdSense.readyState) {
    AdSense.onreadystatechange = function() {
      var rgx = /loaded|complete/g;
      if (rgx.test(AdSense.readyState)) callbackfn();
  } else {
    AdSense.addEventListener("load", callbackfn, false);
Shopping Cart
There are no products in the cart!