Otto
Otto

Reputation: 1685

How is Google analytics gtag supposed to work in a SPA?

From what I can tell, how google recommends to set up gtag, it's a function that is always pushing more variables onto an array:

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

Following the docs on how to use it in a SPA, it seems I'm actually creating a memory leak.

gtag('config', 'GA_TRACKING_ID', {'page_path': '/new-page.html'});
console.log('window.dataLayer', window.dataLayer);

My console shows that every time I navigate to a new page the window.dataLayer array gets larger.

I'm assuming there's something I'm not understanding, because I doubt that Google wants me to create a memory leak in my app, but I'm stumped now.

Upvotes: 7

Views: 1935

Answers (2)

ibrahim tanyalcin
ibrahim tanyalcin

Reputation: 6491

I do not know thoroughly but I assume this is just a normal array initialized before gtag is loaded. If the sole concern is to prevent this array from getting larger, then can't we create an array that prevents itself from getting larger than a set limit? Something like this?:

function createDL(limit){
    var dL = [],//the array
        iCounts = [];//the log of arg. length every time push is called
    dL.push = function(){
        if(this.length >= limit) {
            return (
                !!iCounts[1] 
                && 
                (
                    this.splice(iCounts[0],iCounts[1]),
                    iCounts.splice(1,1),
                    this.push.apply(this,arguments)
                )
            );
        }
        this.constructor.prototype.push.apply(this,arguments);
        iCounts.push(arguments.length);
        return this;
    }
    return dL;
}

Usage:

window.dataLayer = dataLayer || createDL(5);
dataLayer.push(1,2,3);//1,2,3
dataLayer.push(4,5);//1,2,3,4,5
dataLayer.push(6);//1,2,3,6
dataLayer.push(8,9,10,11);//1,2,3,6,8,9,10,11
dataLayer.push("aaa");//1,2,3,"aaa"

I did not touch the first things pushed to dataLayer since they contain the "config" directive and some optional arguments. If the first things pushed to array are larger than the limit, obviously it will always return false and you can't push any longer.

In your case a limit would be 300.

Or am I missing something?

Upvotes: 0

Eduardo
Eduardo

Reputation: 22834

The size of the dataLayer is capped at 300 (FIFO style) currently.

That's not currently documented and likely to change in the future. But the limit is there exactly to avoid blowing up memory in case repeated events happen inside the same page.

Upvotes: 5

Related Questions