Skip to content

Commit

Permalink
Merge pull request googleanalytics#127 from googleanalytics/2.0-dev
Browse files Browse the repository at this point in the history
Version 2.0
  • Loading branch information
philipwalton authored Feb 3, 2017
2 parents e3146a0 + 8618f21 commit 71305bc
Show file tree
Hide file tree
Showing 94 changed files with 7,252 additions and 3,086 deletions.
3 changes: 3 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["es2015"]
}
41 changes: 5 additions & 36 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,45 +1,14 @@
{
"env": {
"browser": true,
"es6": true,
"node": true,
"mocha": true
},
"globals": {
// Used by webdriver.io
"browser": false
"parserOptions": {
"sourceType": "module",
},
"extends": [
"eslint:recommended"
"eslint:recommended",
"google",
],
"rules": {
// possible errors
"no-cond-assign": 0,
"no-empty": 0,
"valid-jsdoc": [2, {
"prefer": {"return": "return"},
"requireReturn": false
}],
// best practices
"no-extra-bind": 2,
// style
"comma-spacing": [2, {"before": false, "after": true}],
"eol-last": [0],
"key-spacing": [2, {"beforeColon": false, "afterColon": true}],
"linebreak-style": [2, "unix"],
"max-len": [2, 80, {"ignoreUrls": true}],
"no-multiple-empty-lines": [2, {"max": 2}],
"no-unused-vars": ["error", {"vars": "all"}],
"no-trailing-spaces": 2,
"object-curly-spacing": [2, "never"],
"quotes": [2, "single"],
"require-jsdoc": [2, {
"require": {
"FunctionDeclaration": true,
"MethodDefinition": true,
"ClassDeclaration": true
}
}],
"semi": [2, "always"],
"semi-spacing": [2, {"before": false, "after": true}],
}
}
11 changes: 6 additions & 5 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ node_modules
npm-debug.log
.DS_Store

# Local SauceLabs test runner
/sauce.sh
# Generated test files
test/unit/index.js
test/unit/index.js.map
test/logs

# Local analytics.js
/analytics.js
/analytics_debug.js
# Local SauceLabs test runner
/test/sauce.sh
7 changes: 2 additions & 5 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@

This document lists the changes between each minor and patch versions. For changes between major versions, see the [Upgrade Reference](/docs/upgrading.md)

## Master (unreleased)
### 2.0.0 (unreleased)

- Update outboundLinkTracker to not use target="_blank" ever
- Fix the in-code version not being automatically updated
- Fix cleanUrlTracker updating `page` on the tracker not just the hit
- Fix outboundFormTracker `formSelector` option not being applied
- See the [Upgrade Reference](/docs/upgrading.md) for a full list of changes.

## 1.1.0 (2016-10-18)

Expand Down
96 changes: 66 additions & 30 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,17 @@

## Overview

The default [JavaScript tracking snippet](https://developers.google.com/analytics/devguides/collection/analyticsjs/) for Google Analytics runs when a web page is first loaded and sends a pageview hit to Google Analytics. If you want to know about more than just pageviews (e.g. events, social interactions), you have to write code to capture that information yourself.
The default [JavaScript tracking snippet](https://developers.google.com/analytics/devguides/collection/analyticsjs/) for Google Analytics runs when a web page is first loaded and sends a pageview hit to Google Analytics. If you want to know about more than just pageviews (e.g. where the user clicked, how far they scroll, did they see certain elements, etc.), you have to write code to capture that information yourself.

Since most website owners care about a lot of the same types of user interactions, web developers end up writing the same code over and over again for every new site they build.

Autotrack was created to solve this problem. It provides default tracking for the interactions most people care about, and it provides several convenience features (e.g. declarative event tracking) to make it easier than ever to understand how people are using your site.
Autotrack was created to solve this problem. It provides default tracking for the interactions most people care about, and it provides several convenience features (e.g. declarative event tracking) to make it easier than ever to understand how people are interacting with your site.

## Plugins

The `autotrack.js` library is small (6K gzipped), and includes the following plugins. By default all plugins are bundled together, but they can be included and configured separately as well. This table includes a brief description of each plugin; you can click on the plugin name to see the full documentation and usage instructions:
The `autotrack.js` file in this repository is small (7K gzipped) and comes with all plugins included. You can use it as is, or you can create a [custom build](#custom-builds) that only includes the plugins you want to make it even smaller.

The following table briefly explains what each plugin does; you can click on the plugin name to see the full documentation and usage instructions:

<table>
<tr>
Expand All @@ -40,6 +42,10 @@ The `autotrack.js` library is small (6K gzipped), and includes the following plu
<td><a href="/docs/plugins/impression-tracker.md"><code>impressionTracker</code></a></td>
<td>Allows you to track when elements are visible within the viewport.</td>
</tr>
<tr>
<td><a href="/docs/plugins/max-scroll-tracker.md"><code>maxScrollTracker</code></a></td>
<td>Automatically tracks how far down the page a user scrolls.</td>
</tr>
<tr>
<td><a href="/docs/plugins/media-query-tracker.md"><code>mediaQueryTracker</code></a></td>
<td>Enables tracking media query matching and media query changes.</td>
Expand All @@ -54,7 +60,7 @@ The `autotrack.js` library is small (6K gzipped), and includes the following plu
</tr>
<tr>
<td><a href="/docs/plugins/page-visibility-tracker.md"><code>pageVisibilityTracker</code></a></td>
<td>Tracks page visibility state changes, which enables much more accurate session, session duration, and pageview metrics.</td>
<td>Automatically tracks how long pages are in the visible state (as opposed to in a background tab)</td>
</tr>
<tr>
<td><a href="/docs/plugins/social-widget-tracker.md"><code>socialWidgetTracker</code></a></td>
Expand All @@ -72,10 +78,10 @@ The `autotrack.js` library is small (6K gzipped), and includes the following plu

To add autotrack to your site, you have to do two things:

1. Load the `autotrack.js` script file on your page.
2. Update your [tracking snippet](https://developers.google.com/analytics/devguides/collection/analyticsjs/tracking-snippet-reference) to [require](https://developers.google.com/analytics/devguides/collection/analyticsjs/using-plugins) the various autotrack plugins you want to use.
1. Load the `autotrack.js` script file included in this repo (or a [custom build](#custom-builds)) on your page.
2. Update your [tracking snippet](https://developers.google.com/analytics/devguides/collection/analyticsjs/tracking-snippet-reference) to [require](https://developers.google.com/analytics/devguides/collection/analyticsjs/using-plugins) the various autotrack plugins you want to use on the [tracker](https://developers.google.com/analytics/devguides/collection/analyticsjs/creating-trackers).

If your site already includes the default JavaScript tracking snippet, you can modify it to look something like this:
If your site is currently using the [default JavaScript tracking snippet](https://developers.google.com/analytics/devguides/collection/analyticsjs/tracking-snippet-reference), you can modify it to something like this:

```html
<script>
Expand All @@ -94,7 +100,7 @@ ga('send', 'pageview');
<script async src='path/to/autotrack.js'></script>
```

Of course, you'll have to make the following modifications to customize autotrack to your needs:
Of course, you'll have to make the following modifications to the above code to customize autotrack to your needs:

- Replace `UA-XXXXX-Y` with your [tracking ID](https://support.google.com/analytics/answer/1032385)
- Replace the sample list of plugin `require` statements with the plugins you want to use.
Expand All @@ -104,46 +110,73 @@ Of course, you'll have to make the following modifications to customize autotrac

### Loading autotrack via npm

If you use npm and a module loader like [Browserify](http://browserify.org/), [Webpack](https://webpack.github.io/), or [SystemJS](https://github.com/systemjs/systemjs), you can include autotrack in your build by requiring it as you would any other npm module:
If you use npm and a module loader that understands [ES2015 imports](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) (e.g. [Webpack](https://webpack.js.org/), [Rollup](http://rollupjs.org/), or [SystemJS](https://github.com/systemjs/systemjs)), you can include autotrack in your build by importing it as you would any other npm module:

```sh
npm install autotrack
```

```js
// In your JavaScript code
require('autotrack');
import 'autotrack';
```

The above code will include all autotrack plugins in your generated source file. If you only want to include a specific set of plugins, you can require them individually:
The above `import` statement will include all autotrack plugins in your generated source file. If you only want to include a specific set of plugins, you can import them individually:

```js
// In your JavaScript code
require('autotrack/lib/plugins/clean-url-tracker');
require('autotrack/lib/plugins/outbound-link-tracker');
require('autotrack/lib/plugins/url-change-tracker');
// ...
import 'autotrack/lib/plugins/event-tracker';
import 'autotrack/lib/plugins/outbound-link-tracker';
import 'autotrack/lib/plugins/url-change-tracker';
```

The above examples show how to include the plugin source code in your final, generated JavaScript file, which accomplishes the first step of the two-step installation process.

You still have to update your tracking snippet and require the plugins you want to use:

The above examples show how to include the autotrack plugin source in your site's main JavaScript bundle, which accomplishes the first step of the [two-step installation process](#installation-and-usage). However, you still have to update your tracking snippet and require the plugins you want to use on the tracker.

```js
// In the analytics.js tracking snippet
// Import just the plugins you want to use.
import 'autotrack/lib/plugins/event-tracker';
import 'autotrack/lib/plugins/outbound-link-tracker';
import 'autotrack/lib/plugins/url-change-tracker';

ga('create', 'UA-XXXXX-Y', 'auto');

// Replace the following lines with the plugins you want to use.
ga('require', 'cleanUrlTracker');
// Only require the plugins you've imported above.
ga('require', 'eventTracker');
ga('require', 'outboundLinkTracker');
ga('require', 'urlChangeTracker');
// ...

ga('send', 'pageview');
```

**Note:** be careful not to confuse the node module [`require`](https://nodejs.org/api/modules.html) statement with the `analytics.js` [`require`](https://developers.google.com/analytics/devguides/collection/analyticsjs/command-queue-reference#require) command. When loading autotrack with an npm module loader, both requires must be used.
#### Code splitting

Note that it's generally not a good idea to include any analytics as part of your site's main JavaScript bundle since analytics are not usually critical application functionality.

If you're using a bundler that supports code splitting (via something like `System.import()`), it's best to load autotrack plugins lazily and delay their initialization until after your site's critical functionality has loaded:

```js
window.addEventListener('load', () => {
const autotrackPlugins = [
'autotrack/lib/plugins/event-tracker',
'autotrack/lib/plugins/outbound-link-tracker',
'autotrack/lib/plugins/url-change-tracker',
// List additional plugins as needed.
];

Promise.all(autotrackPlugins.map((x) => System.import(x)).then(() => {
ga('create', 'UA-XXXXX-Y', 'auto');

ga('require', 'eventTracker', {...});
ga('require', 'outboundLinkTracker', {...});
ga('require', 'urlChangeTracker', {...});
// Require additional plugins imported above.

ga('send', 'pageview');
});
})
```
If you're not sure how do use code splitting with your build setup, see the [custom builds](#custom-builds) section to learn how to manually generate a custom version of autotrack with just the plugins you need.
### Passing configuration options
Expand All @@ -157,21 +190,24 @@ See the individual plugin documentation to reference what options each plugin ac
### Custom builds
The autotrack library is built modularly and each plugin includes its own dependencies, so you can create a custom build of the library using a script bundler such as [Browserify](http://browserify.org/).
Autotrack comes with its own build system, so you can create autotrack bundles containing just the plugins you need. Once you've [installed autotrack via npm](#loading-autotrack-via-npm), you can create custom builds by running the `autotrack` command.
The following example shows how to create a build that only includes the `eventTracker` and `outboundLinkTracker` plugins:
For example, the following command generates an `autotrack.js` bundle and source map for just the `eventTracker`, `outboundLinkTracker`, and `urlChangeTracker` plugins:
```sh
browserify lib/plugins/event-tracker lib/plugins/outbound-link-tracker
autotrack -o path/to/autotrack.custom.js -p eventTracker,outboundLinkTracker,urlChangeTracker
```
When making a custom build, be sure to update the tracking snippet to only require plugins included in your build. Requiring a plugin that's not included in the build will create an unmet dependency, which will prevent subsequent commands from running.
Once this file is generated, you can include it in your HTML templates where you load `analytics.js`. Note the use of the `async` attribute on both script tags. This prevents `analytics.js` and `autotrack.custom.js` from interfering with the loading of the rest of your site.
If you're already using a module loader like [Browserify](http://browserify.org/), [Webpack](https://webpack.github.io/), or [SystemJS](https://github.com/systemjs/systemjs) to build your JavaScript, you can skip the above step and just require the plugins as described in the [loading autotrack via npm](#loading-autotrack-via-npm) section.
```html
<script async src='https://www.google-analytics.com/analytics.js'></script>
<script async src='path/to/autotrack.custom.js'></script>
```
### Using autotrack with multiple trackers
All autotrack plugins support multiple trackers and work by specifying the tracker name in the `require` command. The following example creates two trackers and requires various autotrack plugins on each.
All autotrack plugins support [multiple trackers](https://developers.google.com/analytics/devguides/collection/analyticsjs/creating-trackers#working_with_multiple_trackers) and work by specifying the tracker name in the `require` command. The following example creates two trackers and requires various autotrack plugins on each.
```js
// Creates two trackers, one named `tracker1` and one named `tracker2`.
Expand Down
76 changes: 56 additions & 20 deletions autotrack.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion autotrack.js.map

Large diffs are not rendered by default.

66 changes: 66 additions & 0 deletions bin/autotrack
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#!/usr/bin/env node


/**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


/* eslint no-console: "off" */


const chalk = require('chalk');
const fs = require('fs-extra');
const gzipSize = require('gzip-size');
const minimist = require('minimist');
const path = require('path');
const build = require('./build');
const logErrors = require('./errors');


const argv = minimist(process.argv.slice(2));
const noArgsPassed = Object.keys(argv).length === 1 && argv._.length === 0;
const output = argv.o || argv.output || 'autotrack.js';
const plugins = (argv.p || argv.plugins || '').split(/\s*,\s*/);


if (argv.h || argv.help || noArgsPassed) {
fs.createReadStream(path.join(__dirname, '../bin/usage.txt'))
.pipe(process.stderr);
}
else {
const {cyan, gray, green, red} = chalk;

if (!(plugins.length)) {
console.error(red('At least one plugin must be specified'));
process.exit(1);
}

build(output, plugins)
.then(({code, map}) => {
fs.outputFileSync(output, code, 'utf-8');
fs.outputFileSync(`${output}.map`, map, 'utf-8');

const size = (gzipSize.sync(code) / 1000).toFixed(1);

console.log(green(`\nGreat success!\n`));
console.log(cyan('Built: ') +
`${output} ${gray(`(${size} Kb gzipped)`)}`);
console.log(cyan('Built: ') +
`${output}.map\n`);
})
.catch(logErrors)
.catch(console.error.bind(console));
}
Loading

0 comments on commit 71305bc

Please sign in to comment.