{"id":16323124,"url":"https://github.com/danielstjules/defer-analytics","last_synced_at":"2025-10-31T21:30:28.035Z","repository":{"id":26504779,"uuid":"29957313","full_name":"danielstjules/defer-analytics","owner":"danielstjules","description":"Easily defer loading and firing events for analytics.js","archived":false,"fork":false,"pushed_at":"2015-01-28T08:55:21.000Z","size":120,"stargazers_count":14,"open_issues_count":0,"forks_count":3,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-12-25T22:15:40.638Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/danielstjules.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-01-28T08:14:26.000Z","updated_at":"2022-09-01T19:36:03.000Z","dependencies_parsed_at":"2022-07-08T04:28:29.141Z","dependency_job_id":null,"html_url":"https://github.com/danielstjules/defer-analytics","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danielstjules%2Fdefer-analytics","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danielstjules%2Fdefer-analytics/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danielstjules%2Fdefer-analytics/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danielstjules%2Fdefer-analytics/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/danielstjules","download_url":"https://codeload.github.com/danielstjules/defer-analytics/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239231086,"owners_count":19603990,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-10T22:54:01.238Z","updated_at":"2025-10-31T21:30:27.996Z","avatar_url":"https://github.com/danielstjules.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# defer-analytics\n\nEasily defer loading and firing events for Google Analytic's new web tracking\ncode:\n[analytics.js](https://developers.google.com/analytics/devguides/collection/analyticsjs/).\nAchieves some of the flexibility lost in switching from the soon to be deprecated\n[ga.js](https://developers.google.com/analytics/devguides/collection/gajs/).\nUseful in cleaning up your data and reducing noise by delaying or blocking\nevents for suspicious or illegitimate traffic.\n\n* [Overview](#overview)\n* [Installation](#installation)\n* [Example](#example-use)\n* [License](#license)\n\n## Overview\n\nWith the old ga.js library, one could push as many events as possible onto an\narray, to eventually be handled by Google Analytics once loaded.\n\n``` javascript\nvar _gaq = _gaq || [];\n_gaq.push(['_setAccount', 'UA-XXXXX-X']);\n_gaq.push(['_trackPageview']);\n_gaq.push(['_trackEvent', 'important_event', 'occurred']);\n```\n\nFurthermore, you could previously delay loading google-analytics.com/ga.js\nas much as you'd like. All would still work, for example, while wrapping it\nin a call to setTimeout.\n\n``` javascript\n_gaq.push(['_trackEvent', 'important_event1', 'details']);\n_gaq.push(['_trackEvent', 'important_event2', 'details']);\n\n// Load GA after 5 seconds\nsetTimeout(function() {\n  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n}, 5000);\n```\n\nIn the example above, all events pushed onto _gaq would be processed\nasynchronously at least 5 seconds after page load, plus the latency of loading\nga.js. This, however, is not currently possible with the new analytics.js library.\n\n``` javascript\n// Try to load analytics.js after 5 seconds\nsetTimeout(function() {\n  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\n  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');\n}, 5000);\n\nga('create', 'UA-XXXX-Y', 'auto');\nga('send', 'pageview');\n// ReferenceError: ga is not defined\n```\n\nBut it is with defer-analytics:\n\n``` javascript\n// initAnalytics loads analytics.js after 5 seconds\n// All calls to ga() succeed and are processed once loaded\nsetTimeout(initAnalytics, 5000);\n\nga('create', 'UA-XXXX-Y', 'auto');\nga('send', 'pageview');\n```\n\n## Installation\n\nSimply substitute your existing analytics.js snippet:\n\n``` javascript\n(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\nm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n})(window,document,'script','//www.google-analytics.com/analytics.js','ga');\n\nga('create', 'UA-XXXX-Y', 'auto');\nga('send', 'pageview');\n```\n\nWith:\n\n``` javascript\n(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();\ni.initAnalytics=function(){a=s.createElement(o),m=s.getElementsByTagName(o)[0];\na.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n}})(window,document,'script','//www.google-analytics.com/analytics.js','ga');\n\nga('create', 'UA-XXXX-Y', 'auto');\nga('send', 'pageview');\n\n// Initialize GA when you see fit\ninitAnalytics();\n```\n\nDone.\n\n## Example use\n\nYou run an e-commerce website, a SaaS company, or a personal blog\nfor your pet corgi. Like any good webmaster/developer/digital-marketer, you\nembed the analytics script for tracking visitor behavior, ad spending, and\nconversion!\n\nOne day you find your reports polluted with a segment of daily visitors with\n100% bounce rate. Or who have a session duration of 0.001 seconds. It's a small\nbotnet! And while your site can handle the increase in traffic, your conversion\nrates plummet. You lose insight into your visitor behavior. Your ad retargeting\nbudget is wasted on infected machines. And the GA filters aren't sufficiently\nflexible to remove the noise. What can you do?\n\nYou could delay or avoid loading Google Analytics for those visitors when\nyou detect them. So now you have a bunch of custom `ga('send', ...)` calls\nspread throughout your codebase that need to be wrapped with special logic.\nOr you can just use defer-analytics! Now you can just do something like:\n\n``` javascript\n(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();\ni.initAnalytics=function(){a=s.createElement(o),m=s.getElementsByTagName(o)[0];\na.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n}})(window,document,'script','//www.google-analytics.com/analytics.js','ga');\n\nga('create', 'UA-XXXX-Y', 'auto');\nga('send', 'pageview');\n\nif (legitimateTraffic) {\n  initAnalytics();\n}\n```\n\nIts effectiveness will depend on your ability to isolate the segment based\non different patterns and properties. You also may not want to be so\naggressive in ignoring the segment. An example alternative:\n\n```javascript\nvar initializeOnce = function() {\n  initAnalytics();\n\n  if (window.removeEventListener) {\n    window.removeEventListener('mousemove', initializeOnce, false);\n  } else {\n    window.detachEvent('onmousemove', initializeOnce);\n  }\n};\n\nif (legitimateTraffic) {\n  initAnalytics();\n} else {\n  // Require a mouse movement if a suspected bot\n  if (window.addEventListener) {\n    window.addEventListener('mousemove', initializeOnce, false);\n  } else {\n    window.attachEvent('onmousemove', initializeOnce);\n  }\n}\n```\n\nOf course, it's possible this will only get you so far. You may eventually\nfind yourself needing to export and process the data for analysis, or even\nopt for more reliable analytics with server-side authentication.\n\n## License\n\nUse at your own risk! The code has been modified from the original snippet\nprovided and distributed by Google under the Apache License.\n\n```\nCopyright 2015, Google\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanielstjules%2Fdefer-analytics","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdanielstjules%2Fdefer-analytics","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanielstjules%2Fdefer-analytics/lists"}