Paweł Rychlik Paweł Rychlik - 10 months ago 82
AngularJS Question

Gracefully handling AngularJS Error: $injector:nomod Module Unavailable

My angular app depends on a third-party angular service:

var app = angular.module("ninjaModule", ['angular-google-analytics']);

The app loads up just fine, as long as my ad-blocking plugins are off. However, with ad-blockers on angular throws an
error, failing to load the whole app.

I'm looking for a way to gracefully handle these errors, and therefore be able to load the app regardless of ad-blockers. If angular-google-analytics won't be there - fine, it's not critical, I can deal with it or set up some fallback. But a situation where the whole app crashes is not an option for me. Any ideas?

To be precise - I don't want to work around ad-blockers, e.g. by renaming my script files. I'd expect an angular try-catch magic trick.


Answer Source

I finally got it working. The solution requires a few hacks, though:

  1. checking if angular-google-analytics is loaded
  2. preparing the dependency list (deps) for the main module on the fly
  3. using $injector instead of Analytics explicitly

Still, I need to configure AnalyticsProvider, but it should be relatively easy to do with $injector.

var deps = [];

try {
  angular.module("angular-google-analytics"); // this throws if GA script is not loaded
} catch(e){ console.error("GA not available", e); }

angular.module('mainApp', deps)
.run(function($rootScope, $injector) {
  try {
    Analytics = $injector.get('Analytics');
    $rootScope.trackPage = function() {
      console.log('Analytics in action!');
  } catch(e) {
    $rootScope.trackPage = function(key, label) {
      console.log("Fallback in action!")
.controller('MyCtrl', function($rootScope, $scope) {
  $scope.message = 'Hello World!';

Updated plunker: