How to load js style google analytcs

1

I'm developing a project where I would have to add only one tag on the client site and load js with all the functions. follow 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');

Can anyone help me?

    
asked by anonymous 30.03.2017 / 14:49

1 answer

1

If you organize this minified code it would look 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:

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

I think the third part is what interests you. Putting together the first and second, 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');
    
30.03.2017 / 16:18