How to load js style google Analytcs

Asked

Viewed 44 times

1

I am developing a project where I would have to add only one tag on the client site and already load the js with all functions. follows the example of google Analytcs:

(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
        new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
        })(window,document,'script','dataLayer','IDDDDD');

someone could help me?

1 answer

1


If you organized this code minificado would be like this:

(function(w, d, s, l, i) {
    w[l] = w[l] || [];
    w[l].push({
        'gtm.start': new Date().getTime(),
        event: 'gtm.js'
    });
    var f = d.getElementsByTagName(s)[0],
        j = d.createElement(s),
        dl = l != 'dataLayer' ? '&l=' + l : '';
    j.async = true;
    j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
    f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'IDDDDD');

This code can be analyzed in 3 parts:

  • one closure, to create a scope within this IIFE and be able to have much shorter name variables.
  • fill an array in window.dataLayer
  • insert the script into the DOM, before the first script tag, asynchronous

I think the third part is the one that interests you. Add the first and the second part, you could have something like this:

(function(d, s) {
    var f = d.getElementsByTagName(s)[0],
        j = d.createElement(s);
    j.async = true;
    j.src = 'https://o.teu.url.aqui';
    f.parentNode.insertBefore(j, f);
})(document, 'script');
  • 1

    Man thanks a lot. helped me a lot...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.