首页 > 解决方案 > 如何在外部 .js 文件中运行 Google 跟踪代码管理器脚本?

问题描述

我正在尝试实现 Google 跟踪代码管理器,但希望将 google 提供的代码片段放在我可以加载的外部 .js 文件中。这主要是因为它更容易维护。有些代码必须放在标题中,有些则放在正文中。

我有两个问题:

  1. 是否可以从外部 .js 文件运行脚本,该脚本的外观如何?
  2. 是否可以从同一个 .js 文件运行两个函数?类似于以下内容:
<!-- Let's assume I name the Google Tag Manager JavaScript file to "gtm.js" -->
<!-- The gtm.js contains two functions with one called head and another called body -->

<html>
    <head>
        <title>My Page</title>
        <script type="text/javascript" src="gtm.js, run function: head"></script>
    </head>
    <body>
        <script type="text/javascript" src="gtm.js, run function: body"></script>
    </body>
</html>

谷歌标签管理器头代码:

<!-- 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-xxxxxxx');</script>
<!-- End Google Tag Manager -->

谷歌标签管理器正文代码:

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-xxxxxxx"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

标签: javascripthtml

解决方案


推荐阅读