Skip to content
Advertisement

Why do JS SDKs exposed in window control an arguments array?

I’m building a JS SDK to be exposed in window, and I went to look into how other SDKs do it.

Intercom does this:

var i = function() {
  i.c(arguments);
};
i.q = [];
i.c = function(args) {
  i.q.push(args);
};

Hotjar does this:

h.hj =
  h.hj ||
  function() {
    (h.hj.q = h.hj.q || []).push(arguments);
  };

Pendo does this:

o._q = o._q || [];
v = ['initialize', 'identify', 'updateOptions', 'pageLoad', 'track'];
for (w = 0, x = v.length; w < x; ++w)
  (function(m) {
    o[m] =
      o[m] ||
      function() {
        o._q[m === v[0] ? 'unshift' : 'push'](
          [m].concat([].slice.call(arguments, 0))
        );
      };
  })(v[w]);

But I don’t really understand what is the purpose of this code, and from what little I gathered, it seems related to which methods they expose in their global property.. Is this something I should worry when building a web SDK and should it be in my copy-paste snippet?

Advertisement

Answer

Well, I figured it out myself reading the minified code.

This stuff exists in order to make the methods fully available from the moment the JavaScript is interpreted by the browser, and since it would take some time for the actual JS asset to load via network, you could potentially miss your very first method calls.

Seems like its a queue intended to be used only when the SDK first loads, processing method calls that happened while it was loading.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement