问题
I wish to put the Google Tag Manager code that should be placed in the <head>
of the .html page, in a separate JavaScript file.
Something along the lines of this: <script src="/js/tagmanager.js"></script>
The code that should be placed in the head, provided by google:
<!-- 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','GTM-XXXX');</script>
<!-- End Google Tag Manager -->
How would I rewrite that code to run from the tagmanager.js script file, instead of the script that should be placed in the head? It would be nice if it would load async as well.
回答1:
Place the contents of <script>
into your tagmanager.js file:
(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','GTM-XXXX');
Then load it like this <script async src="/js/tagmanager.js"></script>
来源:https://stackoverflow.com/questions/59445611/run-google-tag-manager-script-inside-of-a-separate-javascript-file