【问题标题】:Does Google Tag Manager execute document.write on custom HTML tags?Google 跟踪代码管理器是否在自定义 HTML 标记上执行 document.write?
【发布时间】:2018-07-18 17:39:53
【问题描述】:

Google 的文档明确指出不支持同步加载标签:https://support.google.com/tagmanager/answer/2787990?hl=en

但是,在创建自定义 HTML 标记时,现在有一个设置“支持 document.write”。这意味着现在支持同步加载标签,但我找不到任何文档来解释新设置的工作原理。

我的问题是:document.write 是否真的被执行了,或者 GTM 是否做了一些聪明的事情,比如在后台用 document.createElement 替换它(如此处所述:http://www.stevesouders.com/blog/2012/04/10/dont-docwrite-scripts/)?

【问题讨论】:

    标签: javascript google-tag-manager


    【解决方案1】:

    GTM 实际上覆盖了 document.write 执行标签的范围(一个自定义的 HTML 标签,支持 document.write,就像你提到的那样),你可以在 Chrome 的 devtools 控制台上看到:

    document.write                                                     
    function (){return m(g(arguments).join(""))}   gtm.js?id=GTM-someid:formatted:1455
    

    一旦 GTM 完成了 document.write 调用,它就会丢弃覆盖:

    document.write
    function write() { [native code] }
    

    它提供的实现使用“普通”插入(例如 document.createElement 后跟 appendChild 或 insertBefore)和一个在脚本加载时运行的侦听器(例如 onreadystatechange 或 onload)并执行放在 document.write 之后的代码调用标签定义。

    【讨论】:

      【解决方案2】:

      我还在 Google+ 页面上针对 Google 跟踪代码管理器提出了这个问题,我得到了 Google 某人的回复:

      “简短回答:GTM 做了一些聪明的事情来支持 doc.write() 异步。”

      https://plus.google.com/108819422004595089210/posts/ZWEXV8FF4tk

      【讨论】:

        【解决方案3】:

        我必须在一个项目中实现类似的功能。从谷歌标签管理器查看缩小的 js 后,我发现他们正在使用这个库:

        https://github.com/krux/postscribe

        GTM 做了一些聪明的事

        确实很聪明:)

        快速 es6 示例:

        import postscribe from 'postscribe'
        const customHtml = "<script>document.write('hello')</script>"
        
        const div = document.createElement('div')
        div.style.display = 'none'
        div.style.visibility = 'hidden'
        document.body.appendChild(div)
        postscribe(div, customHtml)
        

        【讨论】:

          猜你喜欢
          • 2013-07-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-11
          • 2017-09-06
          相关资源
          最近更新 更多