开发者

Can Google Analytics be loaded via AJAX?

开发者 https://www.devze.com 2023-03-21 00:22 出处:网络
The typical Google Analytics code (or rather - the one I was told to add) looks like this: <script type=\"text/javascript\">

The typical Google Analytics code (or rather - the one I was told to add) looks like this:

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-123456-7']);
    _gaq.push(['_setDomainName', '.mydomain.example']);
    _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>

Note the ga.async = true; part. This allows conformant browsers to load the script asynchronously, but there are still plenty of browsers around that don't. I'm worried about performance - I've seen many pages freeze in their loading while trying to download the Google Analytics script. Would it work if I was to load the script via AJAX instead and then eval() it? I'd rather have a page view which was not tracked than a page view that does not load.


You can save this script in a javascript file and load that file after the document.ready event is fired. That way it will not block the loading of page. This is how I include non-essential js and css files (like jquery plugins, ui etc).

Assuming you are using jquery, you can also do this:

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-123456-7']);
    _gaq.push(['_setDomainName', '.mydomain.example']);
    _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]; 
      $(document).ready(function(){
         s.parentNode.insertBefore(ga, s);
      });
    })();
</script>

Note: I've not tested it. I'm just inserting the script element, after document.ready is called.

0

精彩评论

暂无评论...
验证码 换一张
取 消