Código de Google Analytics, optimizado

·

He hablado varias veces de Google Analytics, en general debido al tratamiento sobre el código fuente.

Y es que en general Analytics se suele usar como contador de visitas, en algún caso como medidor de eventos, pero la mayoría como herramienta simple… si ese es tu caso, te recomiendo darle una ojeada a este código de David Kuennen llamado minimal-analytics-snippet.js.

(function (context, trackingId, options) {
    const history = context.history;
    const doc = document;
    const nav = navigator || {};
    const storage = localStorage;
    const encode = encodeURIComponent;
    const pushState = history.pushState;
    const typeException = 'exception';
    const generateId = () => Math.random().toString(36);
    const getId = () => {
        if (!storage.cid) {
            storage.cid = generateId()
        }
        return storage.cid;
    };
    const serialize = (obj) => {
        var str = [];
        for (var p in obj) {
            if (obj.hasOwnProperty(p)) {
                if(obj[p] !== undefined) {
                    str.push(encode(p) + "=" + encode(obj[p]));
                }
            }
        }
        return str.join("&");
    };
    const track = (
        type, 
        eventCategory, 
        eventAction, 
        eventLabel, 
        eventValue, 
        exceptionDescription, 
        exceptionFatal
    ) => {
        const url = 'https://www.google-analytics.com/collect';
        const data = serialize({
            v: '1',
            ds: 'web',
            aip: options.anonymizeIp ? 1 : undefined,
            tid: trackingId,
            cid: getId(),
            t: type || 'pageview',
            sd: options.colorDepth && screen.colorDepth ? `${screen.colorDepth}-bits` : undefined,
            dr: doc.referrer || undefined,
            dt: doc.title,
            dl: doc.location.origin + doc.location.pathname + doc.location.search,
            ul: options.language ? (nav.language || "").toLowerCase() : undefined,
            de: options.characterSet ? doc.characterSet : undefined,
            sr: options.screenSize ? `${(context.screen || {}).width}x${(context.screen || {}).height}` : undefined,
            vp: options.screenSize && context.visualViewport ? `${(context.visualViewport || {}).width}x${(context.visualViewport || {}).height}` : undefined,
            ec: eventCategory || undefined,
            ea: eventAction || undefined,
            el: eventLabel || undefined,
            ev: eventValue || undefined,
            exd: exceptionDescription || undefined,
            exf: typeof exceptionFatal !== 'undefined' && !!exceptionFatal === false ? 0 : undefined,
        });

        if(nav.sendBeacon) {
            nav.sendBeacon(url, data)
        } else {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", url, true);
            xhr.send(data);
        }
    };
    const trackEvent = (category, action, label, value) => track('event', category, action, label, value);
    const trackException = (description, fatal) => track(typeException, null, null, null, null, description, fatal);
    history.pushState = function (state) {
        if (typeof history.onpushstate == "function") {
            history.onpushstate({ state: state });
        }
        setTimeout(track, options.delay || 10);
        return pushState.apply(history, arguments);
    }
    track();
    context.ma = {
        trackEvent,
        trackException
    }
})(window, "XX-XXXXXXXXX-X", {
    anonymizeIp: true,
    colorDepth: true,
    characterSet: true,
    screenSize: true,
    language: true
});

Todo este código se puede comprimir con cualquier herramienta de compresión JavaScript, pero vamos, el código original de más de 50KB queda en menos de 3KB, lo que no solo ayuda en cuanto a tiempo de carga, sino en rendimiento.

Lo importante de este código son las 5 configuraciones del final, que se pueden actualizar.

(window, "XX-XXXXXXXXX-X", {
    anonymizeIp: true,
    colorDepth: true,
    characterSet: true,
    screenSize: true,
    language: true
})

Las últimas versiones, además, dan soporte a eventos y excepciones.

Eventos:

ma.trackEvent('Category', 'Action', 'Label', 'Value')

Excepciones:

ma.trackException('Description', 'Fatal')

Basado en este código, he creado un plugin llamado Minimal Analytics para WordPress, con una configuración muy sencilla.

Comments

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *