How to delay loading an external JS file (Google Analytics)?

I use the following code to download my Google Analytics (external javascript) in a manner that is intended to render the block does not .

However, using YSlow and the Safari Web Inspector, network traffic clearly shows that the ga.js script still blocks parsing.

/*
http://lyncd.com/2009/03/better-google-analytics-javascript/
Inserts GA using DOM insertion of <script> tag and "script onload" method to
initialize the pageTracker object. Prevents GA insertion from blocking I/O!

As suggested in Steve Souder talk. See:
http://google-code-updates.blogspot.com/2009/03/steve-souders-lifes-too-short-write.html
*/

/* acct is GA account number, i.e. "UA-5555555-1" */
function gaSSDSLoad (acct) {
  var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."),
      pageTracker,
      s;
  s = document.createElement('script');
  s.src = gaJsHost + 'google-analytics.com/ga.js';
  s.type = 'text/javascript';
  s.onloadDone = false;
  function init () {
    pageTracker = _gat._getTracker(acct);
    pageTracker._trackPageview();
  }
  s.onload = function () {
    s.onloadDone = true;
    init();
  };
  s.onreadystatechange = function() {
    if (('loaded' === s.readyState || 'complete' === s.readyState) && !s.onloadDone) {
      s.onloadDone = true;
      init();
    }
  };
  document.getElementsByTagName('head')[0].appendChild(s);
}

/* and run it */
gaSSDSLoad("UA-5555555-1");

Any ideas on how I can use JavaScript to delay the loading of the ga.js file, since the above code doesnโ€™t work the way it intends until the whole page is displayed so that I donโ€™t block rendering?

+3
source share
4 answers
/* and run it */
gaSSDSLoad("UA-5555555-1");

, . : . script .

+2

jQuery, ( body onLoad()):

$(window).load(function() {
    /* and run it */
    gaSSDSLoad("UA-5555555-1");
});

, (...):

$(window).load(function() {
    setTimeout("run_it()", 1000);
});

function run_it() {
    /* and run it */
    gaSSDSLoad("UA-5555555-1");
}

, ...

+2

, gaSSDSLoad .

0

, Google Analytics, . - :

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-5555555-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

Google . , javascripts , , :

0

Source: https://habr.com/ru/post/1719763/


All Articles