How to handle locked scripts in requirejs

I am using require js to download Google Analytics. In config I have

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

And I have a module that depends on ga, which initializes the analytics.

Everything works fine until someone uses a browser plugin that blocks Google Analytics. When this happens, the resulting JavaScript error breaks everything.

  • resource upload failed: blocked by client
  • uncaught error: script error for: ga

How can I tell requirejs not have a match if some module fails to load? How to make the module optional?

Thanks.

+7
javascript requirejs google-analytics
source share
3 answers

You can require a module in your own modular code, but beyond the requirements of a particular module, but that means you cannot easily connect to the dependencies you need. i.e.

 define([ /* Normal dependencies here ... */], function() { try { require(['ga']); } catch (error) { // Handle lack of GA if needed } }; 

Alternatively, you will have to write your own module wrapper, which synchronously blocks as it tries, then returns GA if it was successful, or null otherwise.

+3
source share

require takes a third argument, which is an error callback, so you can assign window.ga function that 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(){}; }); 
+3
source share

I found that the best way is to use array notation for path definitions. This way you can define the external URL of the module and the local reserve in the configuration of the requirejs path. No additional try/catch blocks or module-specific error handling is needed.

Documentation link: http://requirejs.org/docs/api.html#pathsfallbacks

I defined a module called noop that defines an empty function, and then configure my paths as follows:

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

+1
source share

All Articles