Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle blocked scripts in requirejs

I am using require js to load google analytics. In config I have

requirejs.config({ "paths": { "ga": "//www.google-analytics.com/analytics", ...

And I have a module that depends on ga that initialises analytics.

Everything works fine until someone uses a browser plugin that blocks google analytics. When that happens, the resulting javascript error breaks everything.

  • failed to load resource : blocked by clien
  • uncaught error: script error for: ga

How can I tell requirejs not to have a fit if a certain module fails to load? How can you make a module optional?

Thanks.

like image 405
herostwist Avatar asked Aug 04 '14 15:08

herostwist


1 Answers

require takes a 3rd argument which is an error callback, so you can assign window.ga to a function which always returns undefined. This avoids errors when calling google analytics functions elsewhere in your code.

require(['ga'], function(data) {
  window.ga('create', 'UA-XXXXXXXX-X');
  window.ga('send', 'pageview');
}, function() {
  window.ga = function(){};
});
like image 107
Brendan Nee Avatar answered Oct 02 '22 02:10

Brendan Nee