dataLayer race condition #62

Closed
robflaherty opened this Issue Jun 2, 2015 · 4 comments

Projects

None yet

2 participants

@robflaherty
Owner

JS error if dataLayer.push() is called before GA converts dataLayer from an array to a function.

@robflaherty robflaherty added the bug label Jun 2, 2015
@bmd
Contributor
bmd commented Jun 3, 2015

dataLayer shouldn't be touched by GA - it's the array-like data object used by GTM. On a page without GTM included, typeof(dataLayer); -> "undefined"

You should be able use the standard dataLayer = dataLayer || [] pattern to initialize it and avoid a race condition on the push method if you need to push something onto it ahead of GTM being initialized but can't guarantee the order in which those things happen.

It seems like the real potential risk for a race condition is here since you aren't checking for the presence of the object you're firing an event to on the actual firing of the event. I think this might also cause a problem if you safe-initialized dataLayer as above and it had type "object" with a valid method push()

@robflaherty
Owner

Hi,
Sorry, I left the bug description brief because this was just a reminder for myself. :)

The problem was this line: standardEventHandler = dataLayer.push; which works after GTM redefines dataLayer but not before when it's still an array. Simply wrapping it like this should fix:

standardEventHandler = function(data) {
  dataLayer.push(data);
}

Testing now and will push to master later today. Thanks.

@robflaherty
Owner

btw, much of this needs to be rewritten. right now i just wanted to get a quick fix out. when i rewrite it i agree it'd be smart to make this more robust and check for the method presence before firing the event.

@bmd
Contributor
bmd commented Jun 3, 2015

Cool - thanks again for maintaining this library.

@robflaherty robflaherty pushed a commit that referenced this issue Jun 8, 2015
Rob Flaherty Fixing #62 to allow events to be pushed onto dataLayer array before G…
…TM initializes
03b36d7
@robflaherty robflaherty closed this Jun 8, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment