Reputation: 2132
Google's documentation clearly states that synchronously loading tags are not supported: https://support.google.com/tagmanager/answer/2787990?hl=en
However there is now a setting 'Support document.write' when creating a custom HTML tag. This implies that synchronously loading tags are now supported but I can't find any documentation to explain how the new setting works.
My question is: Does document.write actually get executed or does GTM do something clever like replace it with document.createElement in the background (as described here: http://www.stevesouders.com/blog/2012/04/10/dont-docwrite-scripts/)?
Upvotes: 3
Views: 6975
Reputation: 1267
I had to implement a similar feature on a project. After looking at minified js from Google Tag Manager, I found out that they were using this library:
https://github.com/krux/postscribe
GTM does something clever
Clever indeed :)
Quick es6 sample:
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)
Upvotes: 0
Reputation: 339
GTM actually overrides document.write for the scope of the executed tag (a custom HTML tag with support for document.write like you mentioned), as you can see on Chrome's devtools console:
document.write
function (){return m(g(arguments).join(""))} gtm.js?id=GTM-someid:formatted:1455
Once GTM has finished the document.write call, it discards the override:
document.write
function write() { [native code] }
The implementation it provides uses "plain" insertion (e.g. document.createElement followed by appendChild or insertBefore) and a listener that runs when the script loads (e.g. onreadystatechange or onload) and executes the code that is placed after the document.write call in the tag definition.
Upvotes: 1
Reputation: 2132
I also asked this question on the Google+ page for Google Tag Manager and I got a response from someone at Google:
"Short answer: GTM does something clever to support doc.write() asynchronously."
https://plus.google.com/108819422004595089210/posts/ZWEXV8FF4tk
Upvotes: 0