Run Google Tag Manager script inside of a separate JavaScript file?

与世无争的帅哥 提交于 2021-01-29 13:12:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!