extract inline JS for google tag manager

This commit is contained in:
Kyle Zhao 2018-09-10 14:10:20 +08:00 committed by Sam
parent 38c70bfda2
commit f666d72606
4 changed files with 24 additions and 11 deletions

View File

@ -0,0 +1,17 @@
(function() {
const gtmDataElement = document.getElementById("data-google-tag-manager");
const dataLayerJson = JSON.parse(gtmDataElement.dataset.dataLayer);
// dataLayer declaration needs to precede the container snippet
// https://developers.google.com/tag-manager/devguide#adding-data-layer-variables-to-a-page
window.dataLayer = [dataLayerJson];
/* eslint-disable */
// prettier-ignore
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer',gtmDataElement.dataset.containerId);
/* eslint-enable */
})();

View File

@ -31,7 +31,7 @@ module ApplicationHelper
if SiteSetting.ga_universal_auto_link_domains.present?
result[:allowLinker] = true
end
result.to_json.html_safe
result.to_json
end
def ga_universal_json

View File

@ -1,11 +1,5 @@
<script>
dataLayer = [<%= google_tag_manager_json %>];
</script>
<meta id="data-google-tag-manager"
data-data-layer="<%= google_tag_manager_json %>"
data-container-id="<%= SiteSetting.gtm_container_id %>" />
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','<%= SiteSetting.gtm_container_id %>');</script>
<!-- End Google Tag Manager -->
<%= preload_script 'google-tag-manager' %>

View File

@ -117,6 +117,8 @@ module Discourse
plugin-third-party.js
markdown-it-bundle.js
service-worker.js
google-tag-manager.js
google-universal-analytics.js
}
# Precompile all available locales