perf(v2): more performant gtag and analytics plugin (#2070)

* perf(v2): more performant gtag and analytics plugin

* more spec compliant

* optimize n refactor

* typo

* review
This commit is contained in:
Endi 2019-12-01 19:55:21 +07:00 committed by GitHub
parent 750d1654a5
commit 046a53ebf4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 124 additions and 89 deletions

View file

@ -5,57 +5,11 @@
* LICENSE file in the root directory of this source tree.
*/
import siteConfig from '@generated/docusaurus.config';
const {themeConfig} = siteConfig;
export default (function() {
if (!themeConfig.googleAnalytics) {
if (typeof window === 'undefined') {
return null;
}
const {trackingID} = themeConfig.googleAnalytics;
if (process.env.NODE_ENV === 'development' && !trackingID) {
console.warn(
'You specified the `googleAnalytics` object in `themeConfig` but the `trackingID` field was missing. ' +
'Please ensure this is not a mistake.',
);
return null;
}
if (
process.env.NODE_ENV !== 'production' ||
!trackingID ||
typeof window === 'undefined'
) {
return null;
}
/* eslint-disable */
(function(i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
(i[r] =
i[r] ||
function() {
(i[r].q = i[r].q || []).push(arguments);
}),
(i[r].l = 1 * new Date());
(a = s.createElement(o)), (m = s.getElementsByTagName(o)[0]);
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m);
})(
window,
document,
'script',
'https://www.google-analytics.com/analytics.js',
'ga',
);
/* eslint-enable */
window.ga('create', trackingID, 'auto');
window.ga('send', 'pageview');
return {
onRouteUpdate({location}) {
// Set page so that subsequent hits on this page are attributed