0

I've been given a function by a client to create a custom script for tracking purposes which is fine, but being new to JS I'm having trouble understanding this line of code:

d[p]=d[p]||function(){(d[p].q=d[p].q||[]).push(arguments);};

function example is:

(function (d,e,k,u,p) {
  d[p]=d[p]||function(){(d[p].q=d[p].q||[]).push(arguments);};     
  var a=e.createElement(k),b=e.getElementsByTagName(k)[0];   a.async=1;a.src=u;b.parentNode.insertBefore(a, b);
}(window,document,'script','https://www.example.com/bundle.js','stringname'));

If anyone could explain it that would be great

Just want to understand the statement better, it works fine and I can copy and paste with the correct url and string name but better if I understand the statement

Salketer
  • 14,263
  • 2
  • 30
  • 58
  • 1
    `d[p]=d[p]||...` is just making sure its defined first. If it isn't, then it assigns the value. – kelsny Nov 30 '22 at 14:53
  • Why was this closed? Seems like a valid question to me... – Ben Aston Nov 30 '22 at 14:57
  • this code is catastrophic when it comes to readabiliy. you need to fix that first. – john-jones Nov 30 '22 at 14:57
  • It translates to something like this: `if (! window['stringname'] ) window['stringname'] = function(...args) { window['stringname'].q.push(...args) }` – adiga Nov 30 '22 at 14:59
  • 1
    It creates a script tag and loads the js url. Note the similarities between this analytics loader and that of [Google tag manager](https://developers.google.com/tag-platform/tag-manager/server-side/dependency-serving) (scroll down to the GTM-ABC code example) – James Nov 30 '22 at 15:11
  • It puts a function on `window.stringname`. That function pushes the arguments sent to it onto a queue (an array) every time it is called. It then downloads and runs `bundle.js`. Without more information, it is hard to say what the purpose of it is. I suspect `window.stringname.q` is used as a staging area for tracking/analytics information, to be sent back to the tracking server as and when another function (probably defined in `bundle.js`) deems it necessary. – Ben Aston Nov 30 '22 at 15:51
  • Thank you all cleared this up it's helped me understand this. – safc2005 Dec 01 '22 at 20:36

0 Answers0