Skip to content

Instantly share code, notes, and snippets.

@kl0tl
Created December 15, 2016 13:39
Show Gist options
  • Save kl0tl/ed0a9e74462a2294f4c8842f5389d8ea to your computer and use it in GitHub Desktop.
Save kl0tl/ed0a9e74462a2294f4c8842f5389d8ea to your computer and use it in GitHub Desktop.
Load Raven async
(function (global, document, url) {
var calls = [];
var spy = {};
var methods = ['config', 'install', 'setUserContext', 'captureException'];
for (var i = 0, method; method = methods[i]; i += 1) {
spy[method] = (function (name) {
return function () {
calls.push([name, arguments]);
return this;
};
}(method));
}
var define = Object.defineProperty;
define(global, 'Raven', {
get: function () { return spy },
set: function (Raven) {
global.removeEventListener('error', captureUnhandledExceptions);
for (var i = 0, exception; exception = unhandledExceptions[i]; i += 1) {
calls.push(['captureException', exception]);
}
define(global, 'Raven', {
value: Raven,
writable: true,
enumerable: true,
configurable: true,
});
for (var i = 0, call; call = calls[i]; i += 1) {
Raven[call[0]].apply(Raven, call[1]);
}
},
enumerable: true,
configurable: true,
});
var unhandledExceptions = [];
function captureUnhandledExceptions(event) {
unhandledExceptions.push([
event.error || new Error(event.message), {
extra: {
file: event.filename,
line: event.lineno,
column: event.colno
}
}
]);
}
global.addEventListener('error', captureUnhandledExceptions);
global.addEventListener('load', function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.crossOrigin = 'anonymous';
script.async = true;
script.src = url;
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
});
}(window, document, 'https://cdn.ravenjs.com/3.9.1/raven.min.js'));
@rmacklin
Copy link

@kl0tl, I found this from getsentry/sentry-javascript#169. Thanks for sharing it!

I have a question regarding this part:

spy[method] = (function (name) {
  return function () {
    calls.push([name, arguments]);
    return this;
  };
}(method));

What does the immediately invoked function provide? Essentially, I'm wondering if this can be replaced by:

spy[method] = function () {
  calls.push([method, arguments]);
  return this;
};

It seems that this will be the spy in either case. Is there something I'm missing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment