mirror of
https://github.com/facebook/docusaurus.git
synced 2025-08-06 10:20:09 +02:00
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:
parent
750d1654a5
commit
046a53ebf4
4 changed files with 124 additions and 89 deletions
|
@ -7,12 +7,64 @@
|
|||
|
||||
const path = require('path');
|
||||
|
||||
module.exports = function() {
|
||||
module.exports = function(context) {
|
||||
const {siteConfig} = context;
|
||||
const {themeConfig} = siteConfig;
|
||||
const {googleAnalytics} = themeConfig || {};
|
||||
|
||||
if (!googleAnalytics) {
|
||||
throw new Error(
|
||||
`You need to specify 'googleAnalytics' object in 'themeConfig' with 'trackingId' field in it to use docusaurus-plugin-google-analytics`,
|
||||
);
|
||||
}
|
||||
|
||||
const {trackingID} = googleAnalytics;
|
||||
|
||||
if (!trackingID) {
|
||||
throw new Error(
|
||||
'You specified the `googleAnalytics` object in `themeConfig` but the `trackingID` field was missing. ' +
|
||||
'Please ensure this is not a mistake.',
|
||||
);
|
||||
}
|
||||
const isProd = process.env.NODE_ENV === 'production';
|
||||
return {
|
||||
name: 'docusaurus-plugin-google-analytics',
|
||||
|
||||
getClientModules() {
|
||||
return [path.resolve(__dirname, './analytics')];
|
||||
return isProd ? [path.resolve(__dirname, './analytics')] : [];
|
||||
},
|
||||
|
||||
injectHtmlTags() {
|
||||
if (!isProd) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
headTags: [
|
||||
{
|
||||
tagName: 'link',
|
||||
attributes: {
|
||||
rel: 'preconnect',
|
||||
href: 'https://www.google-analytics.com',
|
||||
},
|
||||
},
|
||||
// https://developers.google.com/analytics/devguides/collection/analyticsjs/#alternative_async_tag
|
||||
{
|
||||
tagName: 'script',
|
||||
innerHTML: `
|
||||
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
|
||||
ga('create', '${trackingID}', 'auto');
|
||||
ga('send', 'pageview');
|
||||
`,
|
||||
},
|
||||
{
|
||||
tagName: 'script',
|
||||
attributes: {
|
||||
async: true,
|
||||
src: 'https://www.google-analytics.com/analytics.js',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
};
|
||||
};
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue