Search code examples
javascriptgoogle-analyticsrequirejsadblock

GA as RequireJS dependency vs. AdBlock EasyPrivacy list


I have an app (angular, d3, etc) that I'm loading up with require.js. Google Analytics and some other scripts that are blocked by AdBlock's EasyPrivacy list are in the dependency chain, which means the app won't load if the user has it enabled.

I know there are fallback paths if I don't run the optimizer on my scripts to wrap them up, but is there any way to either fall back if they're blocked, or to sniff for the ad blocker and conditionally load a separate config, while still being able to optimize and wrap my scripts?

Maybe something like:

define(function () {
  try {
    var something = require('//path/to/ga');
  } catch (e) {
    return require('fallback');
  }
  return something;
});

using that as the dependency to load GA?

Would something like this work? Is there something I'm missing, or some better way? Can I sniff for AdBlock but only if it's blocking analytics, and load accordingly?


Solution

  • After far too long, I figured out that using :empty in the r.js config, e.g.

    paths: {
        googleAnalytics: ":empty",
        ...
    }
    

    loads the original file(s) called for in main.js including callbacks, so I could add the fallback there:

    paths: {
       googleAnalytics: ['//www.google-analytics.com/analytics', 'ga-fb'],
       ...
    }
    

    where ga-fb.js just loads a script that adds a noop function at window.ga to keep from throwing errors when it's called. The ga-fb.js can't be folded into the optimized file and will load separately if it's needed.

    Probably a beginner-level problem, but I hope this saves someone issues down the road. It was my first project using require.js, so I'm bound to have beginner-level issues.