content,internal: consolidate smaller JS scripts into sitewide entry file

Moves analytics, utm_source and base site code to a new file called
site.ts. This file contains all initialization scripts for pkg.go.dev
that should be run before other scripts are added to the page.

For golang/go#43359

Change-Id: I49dbf7afdaffa9c0638266ae58e1059802936fc1
Reviewed-on: https://go-review.googlesource.com/c/pkgsite/+/299251
Trust: Jamal Carvalho <jamal@golang.org>
Run-TryBot: Jamal Carvalho <jamal@golang.org>
Reviewed-by: Julie Qiu <julie@golang.org>
This commit is contained in:
Jamal Carvalho 2021-03-05 14:58:49 -05:00
Родитель a883572b0a
Коммит fda88804ce
7 изменённых файлов: 151 добавлений и 127 удалений

Просмотреть файл

@ -194,16 +194,7 @@
}
document.head.appendChild(s);
}
loadScript('/static/js/web-vitals.js', {type: 'module', defer: true});
loadScript("/static/js/base.min.js");
if (document.querySelector('.js-gtmID').dataset.gtmid && window.dataLayer) {
window.dataLayer.push(function() {
loadScript('/static/js/utm_source.js', {type: 'module', async: true, defer: true})
})
} else {
loadScript('/static/js/utm_source.js', {type: 'module', async: true, defer: true})
}
loadScript("/static/js/site.js");
</script>
{{block "post_content" .}}{{end}}

Просмотреть файл

@ -1,80 +0,0 @@
/**
* @license
* Copyright 2019-2020 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
(function setupGoogleTagManager() {
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'gtm.start': new Date().getTime(),
event: 'gtm.js',
});
})();
/**
* trackErrors creates an event listener that reports unhandled exceptions
* to Google Tag Manager.
*/
(function trackErrors() {
const loadErrorEvents = (window.__err && window.__err.p) || [];
const trackError = error => {
window.dataLayer.push({
event: 'error',
event_category: 'Script',
event_action: 'uncaught error',
event_label: (error && (error.stack || `${error.name}: ${error.message}`)) || '(not set)',
});
};
for (let event of loadErrorEvents) {
trackError(event.error);
}
window.addEventListener('error', event => {
trackError(event.error);
});
})();
/**
* trackRejections creates an event listener that reports unhandled
* promise rejections to Google Tag Manager.
*/
(function trackRejections() {
const rejectionEvents = new Map();
const reportUnhandledRejections = () => {
for (var reason of rejectionEvents.values()) {
window.dataLayer.push({
event: 'error',
event_category: 'Script',
event_action: 'unhandled rejection',
event_label: (reason && (reason.stack || reason.message)) || '(not set)',
});
}
rejectionEvents.clear();
};
window.addEventListener('unhandledrejection', event => {
rejectionEvents.set(event.promise, event.reason);
// Checking for requestIdleCallback compatibility and
// falling back to setTimeout with arbitrary timeout
// of 250ms.
if (typeof window.requestIdleCallback !== 'undefined') {
window.requestIdleCallback(
() => {
reportUnhandledRejections();
},
{ timeout: 1000 }
);
} else {
window.setTimeout(() => {
reportUnhandledRejections();
}, 250);
}
});
window.addEventListener('rejectionhandled', event => {
rejectionEvents.delete(event.promise);
});
})();

Просмотреть файл

@ -1,34 +1,83 @@
/**
'use strict';
/*!
* @license
* Copyright 2019-2020 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
/**
* A bit of navigation related code for handling dismissible elements.
*/
var _a;
(function registerHeaderListeners() {
'use strict';
const header = document.querySelector('.js-header');
const menuButtons = document.querySelectorAll('.js-headerMenuButton');
menuButtons.forEach(button => {
button.addEventListener('click', e => {
var _a;
e.preventDefault();
header.classList.toggle('is-active');
button.setAttribute('aria-expanded', header.classList.contains('is-active'));
header === null || header === void 0 ? void 0 : header.classList.toggle('is-active');
button.setAttribute(
'aria-expanded',
`${
(_a =
header === null || header === void 0
? void 0
: header.classList.contains('is-active')) !== null && _a !== void 0
? _a
: false
}`
);
});
});
const scrim = document.querySelector('.js-scrim');
if (scrim && scrim.hasOwnProperty('addEventListener')) {
scrim.addEventListener('click', e => {
e.preventDefault();
header.classList.remove('is-active');
header === null || header === void 0 ? void 0 : header.classList.remove('is-active');
menuButtons.forEach(button => {
button.setAttribute('aria-expanded', header.classList.contains('is-active'));
var _a;
button.setAttribute(
'aria-expanded',
`${
(_a =
header === null || header === void 0
? void 0
: header.classList.contains('is-active')) !== null && _a !== void 0
? _a
: false
}`
);
});
});
}
})();
(function setupGoogleTagManager() {
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'gtm.start': new Date().getTime(),
event: 'gtm.js',
});
})();
function removeUTMSource() {
const urlParams = new URLSearchParams(window.location.search);
const utmSource = urlParams.get('utm_source');
if (utmSource !== 'gopls' && utmSource !== 'godoc') {
return;
}
const newURL = new URL(window.location.href);
urlParams.delete('utm_source');
newURL.search = urlParams.toString();
window.history.replaceState(null, '', newURL.toString());
}
if (
((_a = document.querySelector('.js-gtmID')) === null || _a === void 0
? void 0
: _a.dataset.gtmid) &&
window.dataLayer
) {
window.dataLayer.push(function () {
removeUTMSource();
});
} else {
removeUTMSource();
}
//# sourceMappingURL=site.js.map

Просмотреть файл

@ -0,0 +1 @@
{"version":3,"file":"site.js","sourceRoot":"","sources":["site.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;AAUH,CAAC,SAAS,uBAAuB;IAC/B,YAAY,CAAC;IAEb,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC;IACpD,MAAM,WAAW,GAAG,QAAQ,CAAC,gBAAgB,CAAC,sBAAsB,CAAC,CAAC;IACtE,WAAW,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;QAC3B,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE;;YACnC,CAAC,CAAC,cAAc,EAAE,CAAC;YACnB,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,SAAS,CAAC,MAAM,CAAC,WAAW,EAAE;YACtC,MAAM,CAAC,YAAY,CAAC,eAAe,EAAE,GAAG,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,SAAS,CAAC,QAAQ,CAAC,WAAW,oCAAK,KAAK,EAAE,CAAC,CAAC;QAC9F,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,MAAM,KAAK,GAAG,QAAQ,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;IAElD,IAAI,KA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ACrC,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,EAAE,EAAE,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC3D,CAAC;AAED,IAAI,OAAA,QAAQ,CAAC,aAAa,CAAc,WAAW,CAAC,0CAAE,OAAO,CAAC,KAAK,KAAI,MAAM,CAAC,SAAS,EAAE;IACvF,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC;QACpB,eAAe,EAAE,CAAC;IACpB,CAAC,CAAC,CAAC;CACJ;KAAM;IACL,eAAe,EAAE,CAAC;CACnB"}

88
content/static/js/site.ts Normal file
Просмотреть файл

@ -0,0 +1,88 @@
/*!
* @license
* Copyright 2019-2020 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
/**
* site.ts contains a set of functions that should be invoked for
* all page views before other scripts are added to the page.
*/
/**
* A bit of navigation related code for handling dismissible elements.
*/
(function registerHeaderListeners() {
'use strict';
const header = document.querySelector('.js-header');
const menuButtons = document.querySelectorAll('.js-headerMenuButton');
menuButtons.forEach(button => {
button.addEventListener('click', e => {
e.preventDefault();
header?.classList.toggle('is-active');
button.setAttribute('aria-expanded', `${header?.classList.contains('is-active') ?? false}`);
});
});
const scrim = document.querySelector('.js-scrim');
// eslint-disable-next-line no-prototype-builtins
if (scrim && scrim.hasOwnProperty('addEventListener')) {
scrim.addEventListener('click', e => {
e.preventDefault();
header?.classList.remove('is-active');
menuButtons.forEach(button => {
button.setAttribute('aria-expanded', `${header?.classList.contains('is-active') ?? false}`);
});
});
}
})();
interface TagManagerEvent {
event: string;
'gtm.start': number;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface Window {
dataLayer?: (TagManagerEvent | VoidFunction)[];
}
/**
* setupGoogleTagManager intializes Google Tag Manager.
*/
(function setupGoogleTagManager() {
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'gtm.start': new Date().getTime(),
event: 'gtm.js',
});
})();
/**
* removeUTMSource removes the utm_source GET parameter if present.
* This is done using JavaScript, so that the utm_source is still
* captured by Google Analytics.
*/
function removeUTMSource() {
const urlParams = new URLSearchParams(window.location.search);
const utmSource = urlParams.get('utm_source');
if (utmSource !== 'gopls' && utmSource !== 'godoc') {
return;
}
/** Strip the utm_source query parameter and replace the URL. **/
const newURL = new URL(window.location.href);
urlParams.delete('utm_source');
newURL.search = urlParams.toString();
window.history.replaceState(null, '', newURL.toString());
}
if (document.querySelector<HTMLElement>('.js-gtmID')?.dataset.gtmid && window.dataLayer) {
window.dataLayer.push(function () {
removeUTMSource();
});
} else {
removeUTMSource();
}

Просмотреть файл

@ -1,25 +0,0 @@
/**
* @license
* Copyright 2019-2020 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
/**
* removeUTMSource removes the utm_source GET parameter if present.
* This is done using JavaScript, so that the utm_source is still
* captured by Google Analytics.
*/
window.onload = event => {
var urlParams = new URLSearchParams(window.location.search);
var utmSource = urlParams.get('utm_source');
if (utmSource !== 'gopls' && utmSource !== 'godoc') {
return;
}
/** Strip the utm_source query parameter and replace the URL. **/
var newURL = new URL(window.location.href);
urlParams.delete('utm_source');
newURL.search = urlParams.toString();
window.history.replaceState(null, '', newURL.toString());
};

Просмотреть файл

@ -14,7 +14,7 @@ var scriptHashes = []string{
// From content/static/html/base.tmpl
"'sha256-CgM7SjnSbDyuIteS+D1CQuSnzyKwL0qtXLU6ZW2hB+g='",
"'sha256-dwce5DnVX7uk6fdvvNxQyLTH/cJrTMDK6zzrdKwdwcg='",
"'sha256-Q0lBU5W61U2Bjmznl8iFgTCLw4PWCtS1taSwwNz3iGk='",
"'sha256-M35cNZ8vPcaBGw5WTgh0Gn7DLsxkvPbdTFN1pELeevM='",
// From content/static/html/pages/badge.tmpl
"'sha256-T7xOt6cgLji3rhOWyKK7t5XKv8+LASQwOnHiHHy8Kwk='",
// From content/static/html/pages/fetch.tmpl